使用Excel工作表中的输入从vba运行Access SQL查询

时间:2015-07-06 13:19:55

标签: excel vba excel-vba

我每个月都会创建一个表来反映该月的记录。我创建了vba代码,可以在excel中运行多个月的查询来显示更改,新添加等。但是,我希望用户能够从excel下拉框中选择他们想要比较的两个月。我正在努力创建可以执行此操作的动态SQL。以下是我尝试过的代码

`Private Sub ADO_New()

Dim DBFullName As String
Dim Cnct As String, Src As String
Dim Connection As ADODB.Connection
Dim Recordset As ADODB.Recordset
Dim Col As Integer
Dim vCurrentMonth As Variant
Dim vPriorMonth As Variant
Dim wSummary As Worksheet

Set wSummary = Worksheets("Summary")
vCurrentMonth = wSummary.Range("Current_Month").Value
vPriorMonth = wSummary.Range("Prior_Month").Value

Worksheets("New").Cells.ClearContents
DBFullName = ThisWorkbook.Path & "\Guardian_CensusDB.accdb"


Set Connection = New ADODB.Connection
Cnct = "Provider=Microsoft.ACE.OLEDB.12.0;"
Cnct = Cnct & "Data Source=" & DBFullName & ";"
Connection.Open ConnectionString:=Cnct

Set Recordset = New ADODB.Recordset

With Recordset


 Src = "SELECT * FROM [vCurrentMonth] LEFT JOIN [vPriorMonth] ON     
 [vCurrentMonth].[Plan Number] = [vPriorMonth].[Plan Number]" & _
       "WHERE ((([vPriorMonth].[Plan Number]) Is Null))"



.Open Source:=Src, ActiveConnection:=Connection

For Col = 0 To Recordset.Fields.Count - 1
Sheets("New").Range("A1").Offset(0, Col).Value = _
Recordset.Fields(Col).Name
Next

Sheets("New").Range("A1").Offset(1, 0).CopyFromRecordset Recordset

End With


Set Recordset = Nothing

Connection.Close
Set Connection = Nothing



End Sub`

1 个答案:

答案 0 :(得分:0)

您需要将变量连接到字符串中:

Src = "SELECT * FROM [" & vCurrentMonth & "] LEFT JOIN [" & vPriorMonth & "] ON     
 [" & vCurrentMonth & "].[Plan Number] = [" & vPriorMonth & "].[Plan Number]" & _
       "WHERE ((([" & vPriorMonth & "].[Plan Number]) Is Null))"
相关问题