Home > Database > Mysql Tutorial > How to Fix 'Run-time error 3704: Operation is not allowed when object is closed' in Excel VBA When Accessing SQL Databases?

How to Fix 'Run-time error 3704: Operation is not allowed when object is closed' in Excel VBA When Accessing SQL Databases?

Mary-Kate Olsen
Release: 2025-01-01 01:06:11
Original
397 people have browsed it

How to Fix

Accessing SQL Database in Excel-VBA: Resolving Error 3704

In response to the query regarding the "Run-time error 3704: Operation is not allowed when object is closed" encountered while copying data from an SQL database to an Excel sheet using VBA, the answer provided suggests the following modifications:

Modified Code Snippet:

Sub GetDataFromADO()
    'Declare variables'
        Set objMyConn = New ADODB.Connection
        Set objMyRecordset = New ADODB.Recordset
        Dim strSQL As String

    'Open Connection'
        objMyConn.ConnectionString = "Provider=SQLOLEDB;Data Source=localhost;Initial Catalog=MyDatabase;User ID=abc;Password=abc;"
        objMyConn.Open

    'Set and Execute SQL Command'
        strSQL = "select * from myTable"

    'Open Recordset'
        Set objMyRecordset.ActiveConnection = objMyConn
        objMyRecordset.Open strSQL

    'Copy Data to Excel'
        ActiveSheet.Range("A1").CopyFromRecordset (objMyRecordset)

End Sub
Copy after login

Changes Made:

  • Initial Catalog Added: The connection string is now initialized with the "Initial Catalog" parameter, specifying the database to access.
  • Simplified SQL Command: Instead of using ADODB.Command, a simple SQL statement (strSQL) is created and used directly to open the recordset.
  • Field Assignments Simplified: The "Fields["FieldName].Value" format used to assign field values is removed.

By implementing these modifications, the issue with the recordset being closed is resolved, allowing for successful data retrieval and copying to the Excel sheet.

The above is the detailed content of How to Fix 'Run-time error 3704: Operation is not allowed when object is closed' in Excel VBA When Accessing SQL Databases?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template