Reputation: 183
So I am using VBA in Access to create linked tables between Excel and Access. Simple enough and as some online resources guided me I decided to utilize the TransferSpreadsheet command. So I ran some code to test out if I had the syntax correct and got this
DoCmd.TransferSpreadsheet acLink, acSpreadsheetTypeExcel12, _
"Link Name", "File Path", True, "Sheet Name!"
So that worked perfectly, but I wanted to automate it so someone who doesn't understand how to code can use the function. So for the file path I set up a file dialog box to come up so the user can select the excel file. Again worked great.
So now to the point, I want to create a dialog box for users to select the excel sheet to link as well. So essentially the user would select the excel file first and then select from a drop down box the sheet they want to link. Is this possible? If so how would I go about doing it. Here is my code so far:
Public Sub linksheet()
Dim fd As FileDialog
Dim strpath As String
Set fd = Application.FileDialog(msoFileDialogFilePicker)
fd.AllowMultiSelect = False
fd.Title = "Select Routing File"
'get the number of the button chosen
Dim FileChosen As Integer
FileChosen = fd.Show
If FileChosen <> -1 Then
Else
strpath = fd.SelectedItems(1)
DoCmd.TransferSpreadsheet acLink, acSpreadsheetTypeExcel12, _
"Test Link", strpath, True, "Current!"
End If
End Sub
To add to this further I was attempting to utilize this code I found to get the names but I'm unsure how to store them as variables to use.
Public Function WorkSheetNames(strwspath As String) As Boolean
Dim xlApp As Excel.Application
Dim xlBook As Excel.Workbook
Dim xlSheet As Excel.Worksheet
Dim strarray(25)
Set xlApp = CreateObject("Excel.application")
Set xlBook = xlApp.Workbooks.Open(strwspath, 0, True)
For Each xlSheet In xlBook.Worksheets
Debug.Print xlSheet.Name
Next xlSheet
xlBook.Close False
xlApp.Quit
Set xlBook = Nothing
Set xlApp = Nothing
Set xlSheet = Nothing
End Function
What the above code does is list out each sheet name into the debug window, I just am finding it difficult to push those values to an array.
Upvotes: 3
Views: 5818
Reputation: 97101
I don't see why you need to store the sheet names in an array. You could store them as a list in a string variable. Then you could assign that string as the RowSource
property of a combo box which allows the user to select one of the available sheets.
Dim strSheets As String
' adapt your existing code to use this ...
For Each xlSheet In xlBook.Worksheets
'Debug.Print xlSheet.Name
strSheets = strSheets & ";" & xlSheet.Name
Next xlSheet
' discard leading semi-colon
strSheets = Mid(strSheets, 2)
After you have collected the sheet names, apply them as the combo box source.
' ComboName should have Value List as Row Source Type
Me.ComboName.RowSource = strSheets
Upvotes: 2