我在查詢表1從Excel訪問。我正在根據在用戶表單上檢查的三個標準篩選where子句中的列SampleType
。錯誤2147217904查詢從Excel中訪問時,沒有給出一個或多個所需參數的值
我還需要根據where子句中的選擇返回列SampleID
中不同記錄的數目。
我的代碼可能有一些小問題,我無法弄清楚。請幫忙。謝謝
Dim cnn As ADODB.Connection 'dim the ADO collection class
Dim rs As ADODB.Recordset 'dim the ADO recordset class
Dim dbPath As String
Dim SQLwhere As String
Dim StrSql As String
Dim i As Integer
Dim tar6 As String
Dim tar7 As String
Dim tar8 As String
tar6 = "col"
tar7 = "lun"
tar8 = "mel"
'add error handling
On Error GoTo errHandler:
'Disable screen flickering.
Application.ScreenUpdating = False
dbPath = "C:\Users\Temp1\Documents\Annie\MDL_IonTorrent.accdb"
'set the search variable
Set cnn = New ADODB.Connection ' Initialise the collection class variable
cnn.Open "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & dbPath
'Create the SQL statement to retrieve the data from table.
SQLwhere = "WHERE "
If CheckBox2 = True Then
SQLwhere = SQLwhere & "[Table1].[SampleType] LIKE '" & tar6 & "%" & "' AND "
'count a total district records in column SampleID.
End If
If CheckBox3 = True Then
SQLwhere = SQLwhere & "[Table1].[SampleType] LIKE '" & tar7 & "%" & "' AND "
End If
If CheckBox4 = True Then
SQLwhere = SQLwhere & "[Table1].[SampleType] LIKE '" & tar8 & "%" & "' AND "
End If
StrSql = "SELECT COUNT(*) AS UniqueRecordsCount FROM (SELECT DISTINCT [SampleID] FROM [Table1]) "
'Remove the last AND applicable
If SQLwhere = "WHERE " Then
SQLwhere = ""
Else
SQLwhere = Left(SQLwhere, Len(SQLwhere) - 5)
End If
StrSql = StrSql & SQLwhere
'Create the ADODB recordset object.
Set rs = New ADODB.Recordset 'assign memory to the recordset
'ConnectionString Open '--5 aguments--
'Source, ActiveConnection, CursorType, LockType, Options
rs.Open StrSql, cnn
GetDistinctValue = rs("UniqueRecordsCount")
MsgBox (GetDistinctValue)
UserForm1.Controls("txtCrt6").Value = rs!UniqueRecordsCount
'Check if the recordset is empty.
If rs.EOF And rs.BOF Then
'Close the recordet and the connection.
rs.Close
cnn.Close
'clear memory
Set rs = Nothing
Set cnn = Nothing
'Enable the screen.
Application.ScreenUpdating = True
'In case of an empty recordset display an error.
MsgBox "There are no records in the recordset!", vbCritical, "No Records"
Exit Sub
End If
'Close the recordset and the connection.
rs.Close
cnn.Close
'clear memory
Set rs = Nothing
Set cnn = Nothing
'Enable the screen.
Application.ScreenUpdating = True
'error handler
On Error GoTo 0
Exit Sub
errHandler:
'clear memory
Set rs = Nothing
Set cnn = Nothing
MsgBox "Error " & Err.Number & " (" & Err.Description & ") in procedure FindSampleId"
非常感謝。但是,AND語句似乎並不奏效。當我檢查一個文本框時,如果我檢查多個文本框,它總是返回0,我會得到正確的記錄數。如果我不從WHERE子句中減去5,那麼其他問題是錯誤的? – user3781528
您應該使用'OR'而不是'AND'嗎?如果tar6 =「a」,tar7 =「b」,tar8 =「c」,那麼使用AND不會返回任何東西,因爲沒有任何東西是所有這三種東西。使用OR將返回以「a」開頭的任何內容,加上以「b」開頭的任何內容以及以「c」開頭的任何內容。如果你切換到使用OR,那麼只能刪除SQLwhere中的最後4個字符,而不是最後5個 – barrowc
我一定會嘗試'OR'。如果不是從SampleID中選擇不同的值,我想要計算非空白單元格,那麼我需要修改where語句?或者這是一個簡單的修復?謝謝 – user3781528