之前操作VBA代码如下:
Sub SqlFindData()
Dim cnn As Object, rst As Object
Dim Mypath As String, Str_cnn As String, Sql As String
Dim i As Long, j As Long
Set cnn = CreateObject("adodb.connection")
Mypath = ThisWorkbook.FullName
If Application.Version < 12 Then
Str_cnn = "Provider=Microsoft.jet.OLEDB.4.0;Extended Properties=Excel 8.0;Data Source=" & Mypath
Else
Str_cnn = "Provider=Microsoft.ACE.OLEDB.12.0;Extended Properties=Excel 12.0;Data Source=" & Mypath
End If
cnn.Open Str_cnn
'以上后期绑定ADO并建立当前文件链接
For j = 1 To 4
If Len(Cells(2, j).Value) Then
'当查询关键值不为空时,使用and运算符和like链接在一起
Sql = Sql & " AND " & Cells(1, j).Value & " LIKE '%" & Cells(2, j).Value & "%'"
End If
Next
If Len(Sql) = 0 Then MsgBox "尚未输入任一查询关键值。": Exit Sub
'当没有输入任何查询关键值时退出程序
Sql = "SELECT * FROM [学生表$] WHERE " & Mid(Sql, 5)
Set rst = cnn.Execute(Sql)
'cnn.Execute()执行SQL语句
ActiveSheet.UsedRange.Offset(3).ClearContents
For i = 0 To rst.Fields.Count - 1
'遍历记录集中的字段名
Cells(4, i + 1) = rst.Fields(i).Name
Next
Range("a5").CopyFromRecordset rst
'将记录复制到单元格区域
ActiveSheet.ListObjects.Add xlSrcRange, ActiveSheet.UsedRange.Offset(3), , xlYes
'数据区域转换为【表】
cnn.Close '关闭链接
Set cnn = Nothing '释放内存
End Sub