如何使用vba通过检查excel中的列来将数据从excel中获取到Excel中

我已经尝试以下检索信息。 从访问数据库到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列的结果。 但是我没有得到正确的语法。

请帮忙。

  SQL = SQL & "WHERE Material IN (" & range("a1") & "," & range("A2") & " ," & range("a3") & ")" 

您直接用单元格引用replace值,但确保引用在您的语音标记之外。

如果你想做更多的细胞,你可以做

  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 & & ")"