使用Excel和Access一起将变量从excel传递到访问

问题描述 投票:0回答:2

在excel中,我有一个链接表到访问表“tbl_Output”

目前有一个手动步骤,在运行excel宏之前,我必须进入数据库并打开一个创建表查询并手动输入一个条件并运行。称之为“供应商名称”字段

此供应商名称存在于Excel文档中。是否可以在excel中声明该变量,将其传递给访问并使用该变量作为其条件运行create table查询。

该任务为许多供应商运行,因此如果我可以自动执行此步骤,我可以创建一个循环来遍历所有供应商。

我已经尝试了一种解决方法,通过将一个链接数据透视表连接到创建表查询所基于的数据源,然后在excel数据透透表本身中进行过滤,但由于大量数据,刷新需要太长时间。

如果这是显而易见的事情,请道歉。使用访问权限编码vba是我不熟悉的。

excel vba ms-access access-vba
2个回答
0
投票

对于被问到的问题不是100%,但是我会考虑一下。下面的代码将采用供应商名称[供应商ID]的列表,并将遍历列表,为每个包含该特定供应商的信息的供应商ID执行创建表查询。

Sub umCreateDBTables()
    Dim DBPath As String ' Path to the database with the information
    Dim DBPath2 As String ' Path to the database to store the newly created tables in
    Dim xlCell As Range
    Dim sSQL As String
    Dim DB As DAO.Database
    Dim VenID As String
    Dim i As Integer
        DBPath = "C:\DB_Temp\AccessDB_A.accdb"
        DBPath2 = "C:\DB_Temp\AccessDB_B.accdb"
        Set DB = OpenDatabase(DBPath, True, False)
        Set xlCell = Range("A2") ' Assumes that this is the beginning of the column with your vendor ids
        Do Until xlCell.Value = "" ' Loops through the list of vendor ids until it gets to an empty cell
            VenID = "v_" & xlCell.Value ' would be best to feed this through a function to strip out any invalid db field name characters
            sSQL = "SELECT T1.F1, T1.F2, T1.F3, INTO " & VenID & " IN '" & DBPath2 & "' FROM T1 WHERE (((T1.F1)='" & xlCell.Value & "'));"
            For i = DB.TableDefs.Count - 1 To 0 Step -1 ' Cycle through the list of database objects [tables, queries, etc....]
                If DB.TableDefs(i).Name = VenID Then ' If the vendor table already exists in the DB, delete it so it can be recreated
                    DB.TableDefs.Delete (VenID)
                End Select
            Next i
            DB.Execute sSQL ' Run the SQL to create the vendor table
            Set xlCell = xlCell.Offset(1, 0) ' move down to the next row
        Loop
        DB.Close
        Set DB = Nothing
        Set xlCell = Nothing
End Sub

希望这可以帮助


0
投票

非常感谢Glenn G.

您提供的代码非常有用,让我朝着正确的方向前进。

我有DAO的运行时问题,即使添加了参考但是解决了它。

我开始工作的代码是:

Sub UpdateDatabase()
Dim DBPath As String
Dim xlcell As Range
Dim sSQL As String, stProvider As String
Dim DB As New ADODB.Connection
    DBPath = "C:\Temp\Data.accdb"
    stProvider = "Microsoft.ACE.OLEDB.12.0"
    With DB
        .ConnectionString = DBPath
        .Provider = stProvider
        .Open
    End With
    Set xlcell = Sheet3.Range("X2")
    Do Until xlcell.Value = ""
        venid = xlcell.Value
        sSQL = "SELECT ALL * INTO tbl_Output FROM qry_Data WHERE (((qry_Data.VendorName)='" & xlcell.Value & "'));"
        DB.Execute "DROP TABLE tbl_Output;"
        DB.Execute sSQL
        Set xlcell = xlcell.Offset(1, 0)
    Loop
    DB.Close
    Set DB = Nothing
    Set xlcell = Nothing

再次感谢你的帮助。

问候

理查德

© www.soinside.com 2019 - 2024. All rights reserved.