简体   繁体   English

使用VBA将Access查询输出导入Excel

[英]Importing Access query output into Excel using VBA

I am trying to get this code to work, but it doesn't seem to want to pull the string from the getopenfilename command, so I thought I would see if anybody has any ideas on how to reconfigure this code so that it will not treat the getopenfilename string as text and instead as a real path... 我正在尝试使此代码正常工作,但是它似乎不想从getopenfilename命令中提取字符串,因此我想我是否可以对是否有任何关于如何重新配置​​此代码的想法有所了解,以至于不予处理getopenfilename字符串作为文本而不是真实路径...

Sub DB_Import()
    Dim FilePath As Variant

    MsgBox ("Select the path and filename of the correct database")
    FilePath = Application.GetOpenFilename

    With ActiveSheet.ListObjects.Add(
        SourceType:=0, 
        Source:=Array( _
            "OLEDB;Provider=Microsoft.ACE.OLEDB.12.0;Password="""";User ID=Admin; " & _
            "DataSource=FilePath;Mode=Share Deny Write;Extended Properties=""""; " & _
            "Jet OLEDB:System database="""";Jet OLEDB:Registry Path=""""; " & _
            "Jet OLEDB:Database Password="""";Jet OLEDB:Engine Type=6;" & _
            "Jet OLEDB:Database Locking Mode=0;Jet OLEDB:Global Partial Bulk Ops=2;" & _
            "Jet OLEDB:Global Bulk Transactions=1;Jet OLEDB:New Database Password="""";" & _
            "Jet OLEDB:Create System Database=False;Jet OLEDB:Encrypt Database=False;Jet " & _
            "OLEDB:Don't Copy Locale on Compact=False;Jet OLEDB:Compact Without Replica Repair=False;" & _
            "Jet OLEDB:SFP=False;Jet OLEDB:Support Complex Data=False;" & _
            "Jet OLEDB:Bypass UserInfo Validation=False"), 
        Destination:=Range("$A$1")).QueryTable

        .CommandType = xlCmdTable
        .CommandText = Array("Query1")
        .RowNumbers = False
        .FillAdjacentFormulas = False
        .PreserveFormatting = True
        .RefreshOnFileOpen = False
        .BackgroundQuery = True
        .RefreshStyle = xlInsertDeleteCells
        .SavePassword = False
        .SaveData = True
        .AdjustColumnWidth = True
        .RefreshPeriod = 0
        .PreserveColumnInfo = True
        .SourceDataFile = FilePath
        .ListObject.DisplayName = "Table_ExternalData_1"

        .Refresh BackgroundQuery:=False
    End With
End Sub

Change the 2nd line to this: 将第二行更改为:

"DataSource=" & FilePath & ";Mode=Share Deny Write;Extended Properties=""""; " & _

That will insert the value of FilePath into your connection string. 这会将FilePath的值插入到您的连接字符串中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM