我想将Access中的表(Table1)中的数据以编程方式导入到Excel中。 我在userform(txtCr1& txtCr2)上有两个搜索框和一个执行代码的按钮。每个搜索框对应于表1中的字段。我想搜索使用“AND”来搜索这两个字段。我不知道我的代码中缺少什么,但是当我运行它时我得到错误3001。请建议如何解决此问题。
提前感谢您的帮助。
Private Sub CommandButton5_Click()
'Declaring the necessary variables.
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 SrtSql As String
Dim i As Integer
Dim var
Dim var2
'add error handling
On Error GoTo errHandler:
'Disable screen flickering.
Application.ScreenUpdating = False
'clear the values from the worksheet
Sheet5.Range("A2:AD499").ClearContents
'get the path to the database
dbPath = Sheet5.Range("H500").Value
'set the search variable
var = UserForm1.txtCrt1
var = UserForm1.txtCrt2
Set cnn = New ADODB.Connection ' Initialise the collection class variable
'Connection class is equipped with a —method— named Open
'—-4 aguments—- ConnectionString, UserID, Password, Options
'ConnectionString formula—-Key1=Value1;Key2=Value2;Key_n=Value_n;
cnn.Open "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & dbPath
'Create the SQL statement to retrieve the data from table.
SQLwhere = "WHERE "
If Len(var & vbNullString) <> 0 Then
SQLwhere = SQLwhere & "[Table1].[RunDate] = '" & var & "' AND "
End If
If Len(var2 & vbNullString) <> 0 Then
SQLwhere = SQLwhere & "[Table1].[SampleID] = '" & var2 & "' AND "
End If
StrSql = "SELECT * FROM [Table1] "
'Remove the last AND applicable
If SQLwhere = "WHERE " Then
SQLwhere = ""
Else
SQLwhere = Left(SQLwhere, Len(SQLwhere) - 4)
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 sql, cnn
'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"
'Me.lstDataAccess.RowSource = ""
Exit Sub
End If
'Write the reocrdset values in the sheet.
Sheet5.Range("A2").CopyFromRecordset rs
'Close the recordset and the connection.
rs.Close
cnn.Close
'clear memory
Set rs = Nothing
Set cnn = Nothing
'Enable the screen.
Application.ScreenUpdating = True
'Inform the user that the macro was executed successfully.
MsgBox "Congratulation the data has been successfully Imported", vbInformation, "Import successful"
'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 Import_Data"
End Sub