CodexBloom - Programming Q&A Platform

Excel VBA: How to retrieve data from a closed workbook without opening it?

👀 Views: 48 đŸ’Ŧ Answers: 1 📅 Created: 2025-06-05
vba excel ado

I'm trying to read data from a closed Excel workbook using VBA, but I keep working with the 'Method 'Range' of object '_Global' failed' behavior. My goal is to extract specific values from a closed workbook without opening it, as it contains sensitive data that should not be exposed unnecessarily. I've been using the following code, which utilizes the ADO connection method: ```vba Sub ReadFromClosedWorkbook() Dim conn As Object Dim rs As Object Dim strSQL As String Dim filePath As String filePath = "C:\path\to\your\file.xlsx" strSQL = "SELECT * FROM [Sheet1$] WHERE [ID] = '001'" Set conn = CreateObject("ADODB.Connection") Set rs = CreateObject("ADODB.Recordset") conn.Open "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & filePath & ";Extended Properties='Excel 12.0 Xml;HDR=YES;' rs.Open strSQL, conn, 1, 3 If Not rs.EOF Then MsgBox "Value: " & rs.Fields(0).Value Else MsgBox "No data found." End If rs.Close conn.Close End Sub ``` I've checked that the path and sheet name are correct. However, I am unsure if the scenario lies with the SQL query or the connection string. I'm using Excel 2010 on Windows 10 and have the ACE OLEDB provider installed. I've also tried using different versions of the OLEDB provider, but I still encounter the same behavior. Any suggestions on how to troubleshoot this or alternative methods to read data from a closed workbook? Thanks for any help you can provide!