我已尝试以下方法来检索信息。从访问数据库到excel文件:
Sub ddd()
Const dbloc As String = "C:\Users\mysystem1\Downloads\Database11.accdb"
Dim db As DAO.Database
Dim rs As DAO.Recordset
Dim xlbook As Workbook
Dim xlsheet As Worksheet
Dim a As Long
Dim SQL As String
Set xlbook = ActiveWorkbook
Set xlsheet = xlbook.Worksheets(1)
xlsheet.Range("A5:Z100000").ClearContents
Application.StatusBar = "Connecting to external database..."
Set db = OpenDatabase(dbloc)
SQL = "SELECT Material_ID "
SQL = SQL & "FROM Sheet1"
'Sheet1 is the the access tablename
'SQL = SQL & "WHERE Material IN (500017,500024,500029)"
' i want to update the where condition above to a column in the excel wb itself
Set rs = db.OpenRecordset(SQL, dbOpenSnapshot)
If rs.RecordCount = 0 Then
MsgBox "No data retrieved from database", vbInformation + vbOKOnly, "No Data"
GoTo SubExit
Else
rs.MoveLast
recCount = rs.RecordCount
rs.MoveFirst
End If
xlsheet.Range("C5").CopyFromRecordset rs
End Sub
我想更新sql查询中的where条件,以根据Excel wb中的列返回结果。但我没有得到正确的语法。
请帮忙。
答案 0 :(得分:1)
SQL = SQL & "WHERE Material IN (" & range("a1") & "," & range("A2") & " ," & range("a3") & ")"
您实际上会使用单元格引用替换值,但请确保引用位于语音标记之外。
如果你想做更多细胞,你可以做
SQL = SQL & "WHERE Material IN ("
Dim r as range
For each r in range("a1:A20")
SQL = SQL & r.text & ","
Next r
SQL = left(SQL,LEN(SQL)-1) 'Drop last comma
Sql = SQL & & ")"