gpt4 book ai didi

excel - 允许 Access 用户选择 Excel 工作表进行链接

转载 作者:行者123 更新时间:2023-12-02 20:19:02 25 4
gpt4 key购买 nike

因此,我在 Access 中使用 VBA 在 Excel 和 Access 之间创建链接表。足够简单,根据一些在线资源的指导,我决定使用 TransferSpreadsheet 命令。所以我运行了一些代码来测试我的语法是否正确并得到了这个

DoCmd.TransferSpreadsheet acLink, acSpreadsheetTypeExcel12, _
"Link Name", "File Path", True, "Sheet Name!"

所以效果很好,但我想将其自动化,以便不了解如何编码的人可以使用该功能。因此,对于文件路径,我设置了一个文件对话框,以便用户可以选择 Excel 文件。再次效果很好。

现在,我想创建一个对话框,供用户选择要链接的 Excel 工作表。因此,基本上用户会首先选择 Excel 文件,然后从下拉框中选择他们想要链接的工作表。这可能吗?如果是这样,我将如何去做。这是到目前为止我的代码:

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

为了进一步补充这一点,我试图利用我发现的这段代码来获取名称,但我不确定如何将它们存储为要使用的变量。

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

上面的代码的作用是将每个工作表名称列出到调试窗口中,我只是发现很难将这些值推送到数组中。

最佳答案

我不明白为什么您需要将工作表名称存储在数组中。您可以将它们作为列表存储在字符串变量中。然后,您可以将该字符串指定为组合框的 RowSource 属性,该属性允许用户选择可用的工作表之一。

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)

收集工作表名称后,将它们应用为组合框源。

' ComboName should have Value List as Row Source Type
Me.ComboName.RowSource = strSheets

关于excel - 允许 Access 用户选择 Excel 工作表进行链接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20079882/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com