VBA Excel 从关闭的文件中获取工作簿对象或通过 sheet 索引引用 Excel SQL Table

VBA Excel get workbook object from closed file or refer to Excel SQL Table by sheet index

我希望能够定义一个 Workbook 对象并在不打开工作簿的情况下获取有关其 Worksheets 对象的信息。

我有一个工作簿的 name/path 和一个代表 Worksheet 的索引,我想得到作品的名称sheet。

此外,我想这样做的原因是我随后想将关闭的工作簿中的 sheet 称为 excel table 我可以使用SQL 个语句。

所以最终我需要能够构造一个字符串,例如“SELECT * FROM [Sheet1$]”,其中“Sheet1”是引用的已关闭工作簿中 sheet 的名称按已知指数。

所以一个更精确的问题是我可以通过索引而不是名称在 SQL 语句中引用 sheet 吗?

但如果不行,是否可以将工作sheet对象设置为已关闭工作簿中的sheet?

这有效,但显然我打开和关闭了文件。感谢任何 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


这是一种无需打开工作簿即可获取 sheet 名称以及工作簿中任何命名范围的名称的方法。

不确定 how/if 它是否适用于 sheet 索引。

Sub GetSheetAndRangeNames()
Dim con As Object
Dim cat As Object
Dim tbl As Object

    Set con = CreateObject("ADODB.Connection")
    con.Provider = "Microsoft.ACE.OLEDB.12.0;Data Source=c:\Users\Norie\Documents\Test.xlsx;Extended Properties='Excel 12.0 Xml';"
    con.Open
    Set cat = CreateObject("ADOX.Catalog")
    Set cat.ActiveConnection = con

    For Each tbl In cat.Tables
        Debug.Print tbl.Name
    Next tbl

End Sub

使用 Dao,您可以通过索引号获取 sheet 名称。索引从0开始。

Sub getDaoTableName()
    Dim fn As String
    Dim conn As Object, db As Object
    Dim tbl As Object
    
    fn = ThisWorkbook.Path & Application.PathSeparator & "test_file.xlsx"

    Set conn = CreateObject("DAO.DBEngine.120")
    Set db = conn.OpenDatabase(fn, False, True, "Excel 12.0 Xml;HDR=Yes;")
    
    Set tbl = db.TableDefs(0) ' 0 is Sheets(1) : 1 is Sheets(2)
    MsgBox tbl.Name

    Set db = Nothing
    Set conn = Nothing

End Sub