When attempting to retrieve data from a SQL database into an Excel sheet using VBA code, users may encounter Runtime Error 3704, indicating an invalid operation with a closed object. This typically occurs during the step where data is copied from the recordset to the Excel sheet.
One potential cause of this error lies in the connection string. Ensure that the connection string includes the Initial Catalog parameter, specifying the name of the database to be accessed. Here's an updated connection string with the parameter:
objMyConn.ConnectionString = "Provider=SQLOLEDB;Data Source=localhost;Initial Catalog=MyDatabase;User ID=abc;Password=abc;"
Another issue may be the use of an extra layer of indirection when specifying the SQL command. To simplify the code and avoid the error, you can directly use an SQL statement string as follows:
strSQL = "select * from myTable"
Then, open the recordset using the SQL statement string as the command text:
objMyRecordset.Open strSQL
By addressing these potential issues and ensuring that the connection string is complete and that the SQL command is executed correctly, you should be able to successfully retrieve data from the SQL database into your Excel sheet using VBA.
The above is the detailed content of Why Am I Getting Runtime Error 3704 When Accessing a SQL Database in Excel VBA?. For more information, please follow other related articles on the PHP Chinese website!