基于两个参数从Access表导入Excel

时间:2012-02-03 19:34:47

标签: excel ms-access vba

我正在尝试根据两个参数将数据从Access导入Excel。我有一个工具列表,用于指定项目编号(参数1)和工具类型(参数2)。如何过滤掉不满足用户输入这两个参数的工具?

我看到了这个帖子:Import to Excel from Access table based on parameters

但它没有谈论多个参数。这是我到目前为止所处的位置:

    Dim cn As Object
Dim rs As Object
Dim strFile As String
Dim strCon As String
Dim strSQL As String
Dim s As String
Dim i As Integer, j As Integer

''Access database

strFile = "D:\Tool_Database\Tool_Database.mdb"

''This is the Jet 4 connection string, you can get more
''here : http://www.connectionstrings.com/excel

strCon = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & strFile & ";"

''Late binding, so no reference is needed

Set cn = CreateObject("ADODB.Connection")
Set rs = CreateObject("ADODB.Recordset")

cn.Open strCon

'Find the name of the tool that was selected
Dim SelectedTool As String, SelectedProj
Set SelectedTool = Tools_ListBox.Selected
Set SelectedProj = Project_ListBox.Selected

strSQL = "SELECT * " _
        & "FROM ToolFiles " _
        & "WHERE Tool_Name = '" & SelectedTool & "'"

rs.Open strSQL, cn, 3, 3

Worksheets("ToolList").Cells(2, 1).CopyFromRecordset rs

rs.Close
Set rs = Nothing
cn.Close
Set cn = Nothing

显然,strSQL语句是我需要集中注意力并将值插入SelectedProj的地方。

谢谢!

2 个答案:

答案 0 :(得分:1)

如果您只想将SelectedProj添加到SQL语句中,这应该是技巧(其中ProjectType是字段的名称):

strSQL = "SELECT * " _
        & "FROM ToolFiles " _
        & "WHERE Tool_Name = '" & SelectedTool & "' " _
        & "AND ProjectType = '" & SelectedProj & "'"

答案 1 :(得分:0)

如果选择的项目在上面的示例中没有意义,则selected属性返回True。也许你正在寻找像

这样的东西
SelectedTool = Tools_listbox.Items(Tools_listbox.SelectedItem)

请注意,你也没有一个顽皮的SelectedTool声明,但我想它应该是一个字符串,在这种情况下你不应该使用Set。