I want to set up a VBA routine that will open up a specific Excel sheet, get
the tab names, store them in a table then close. The tab names and number of
tabs can vary so I need to be able to retrieve as many as there are. I will
then use this to import the data in each of the tabs. Any ideas? TIA....
Create a new Table.
TableName "tblWorksheetNames"
Field Name "SheetName" Text datatype, Indexed Yes/No Duplicates
Create a new Module.
Click on tools + references
Set a reference to the Microsoft Excel 10.0 Object Library.
Then copy and paste the below code into the module
Public Sub GetWorksheetNames()
On Error GoTo Err_Handler
Dim xlx As Object, xlw As Object
Set xlx = CreateObject("Excel.Application")
Set xlw = xlx.workbooks.Open("C:\MyFolderName\SpreadsheetName.xls", ,
True)
Dim S As Excel.Worksheet
For Each S In xlw.Worksheets
CurrentDb.Execute "Insert Into tblWorksheetnames(SheetName)
Values('" & S.Name & "');", dbFailOnError
Next S
Exit_Sub:
xlw.Close False
Set xlw = Nothing
xlx.Quit
Set xlx = Nothing
Exit Sub
Err_Handler:
If Err = 3022 Then
Resume Next
Else
MsgBox "Error: " & Err.Number & " " & Err.Description
Resume Exit_Sub
End If
End Sub
Run the code. The sheet names will be added to the table. No name will
be duplicated.