I would like to be able to define a Workbook object and get info about its Worksheets object without opening the workbook.
I have the name/path of a workbook and an index representing a Worksheet in it and I would like to get the name of the worksheet.
Furthermore, the reason I want to do this is that I subsequently want to refer to the sheet in the closed workbook as an excel table that I can operate on using SQL statements.
So ultimately I need to be able to construct a string such as "SELECT * FROM [Sheet1$]" where "Sheet1" is the name of the sheet in the closed workbook referenced by the known index.
So a more precise question is can I refer to a sheet in an SQL statement by index rather than name?
But if not, is it possible to set a worksheet object to a sheet in a closed workbook?
This works but obviously I open and close the file. Thanks for any help/insight
Option Explicit
Sub get_sheetname_from_index()
Dim full_path_and_name As String
full_path_and_name = Application.ThisWorkbook.Path & _
Application.PathSeparator & "test_file.xlsx"
Dim index As Long
index = 1
Dim wb As Workbook
Set wb = Application.Workbooks.Open(full_path_and_name, ReadOnly:=True)
Dim closed_file_sheet_name As String
closed_file_sheet_name = wb.Worksheets(index).Name
Dim x As Worksheet
Set x = wb.Sheets(1)
wb.Close savechanges:=False
Debug.Print closed_file_sheet_name
' USe the file name here
Dim connection As New ADODB.connection
connection.ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data _
Source= " & full_path_and_name & _
";Extended Properties=""Excel 12.0;HDR=YES;"""
connection.Open
Dim sql As String
sql = "SELECT * FROM [" & closed_file_sheet_name & "$]"
Dim rs As New ADODB.Recordset
rs.Open sql, connection
While Not rs.EOF
Debug.Print rs.Fields(0).Name, rs.Fields(0).Value
rs.MoveNext
Wend
rs.Close
connection.Close
End Sub