使用动态输入参数将访问查询连接到excel

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

我有一些查询已连接到我刷新的Excel工作表以获取最新数据。

有可能让excel“询问”一列的输入参数吗?

我希望公司获取数据,因此想知道是否有可能在访问(类型[公司] :)的现场标准中这样做

如果我在访问中保存这样的查询,它将不允许我将它连接到excel

谢谢

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

还好另一个编辑。

在这里,我创建了一个数据库,它很简单。该数据库名为“Database1.accdb”

enter image description here

屏幕截图中显示的记录多于记录。

我用一张表创建了一个工作簿,它的名字是“AccessDBtest.xlsm”

我在Sheet1上创建了一个按钮,并在其旁边的单元格中输入了我想要的字段参数,C3或(3,3)(行,列)格式。

这是根据输入条件返回数据集(没有字段名称)的代码。我在SQL查询执行之前创建了一个msgBox,以便我可以先查看它。如果你不想要它,你不需要它,有利于测试。

Private Sub CommandButton1_Click()
Dim inputSheet As Worksheet
Dim fieldSTR As String
Dim placementRange As Range

Dim rs As Object 'record set

Dim conn As Object
Dim strQuery As String

Dim myDB As String

Set inputSheet = ThisWorkbook.Worksheets("Sheet1")
Set placementRange = inputSheet.Range("E2")

fieldSTR = CStr(inputSheet.Cells(3, 3).Value) 'C3 cell

myDB = "C:\Users\Documents\0_Excel Projects\Testing\Database1.accdb"

Set conn = CreateObject("ADODB.Connection")

    With conn
        .Provider = "Microsoft.ACE.OLEDB.12.0"    'For *.ACCDB Databases
        .ConnectionString = myDB
        .Open
    End With


strQuery = "SELECT * FROM " & _
            "tbl_test WHERE tbl_test.Color = " & "'" & fieldSTR & "'" & ";"

'The below gives the same result as * but you could limit the fields returned as well
'tbl_test.ID, tbl_test.Color, tbl_test.number

'just using Color also works you do not need to reference the table directly

MsgBox (strQuery)

Set rs = conn.Execute(strQuery)

placementRange.CopyFromRecordset rs

rs.Close
Set rs = Nothing
conn.Close
Set conn = Nothing

End Sub

看看你是否可以使用它来映射你想要做的事情。我想从单元格中捕获一个字符串,然后在查询中使用该字符串。

这是查询执行之前的MsgBox(访问将会看到):我用*测试了所有字段,下面你可以看到我调用了特定的字段,它们都有效。

enter image description here

这是我清除msgBox后发生的事情,记录集被拉出并粘贴在我指定的范围内的范围。(“E3”)开始我指定的工作表(Sheet1)enter image description here

如您所见,我们可以使用当前工作表中的输入从数据库中提取查询。

如果这有助于您的情况,请告诉我。

如果需要,我们可以深入挖掘。

-WWC

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