大家好,今日继续讲解《VBA数据库解决方案》,今日讲解的内容是:利用ADO,实现模糊查询。在上一讲中,我们实现了利用ADO快速查找的功能,今日我们实现工作表中模糊查找的功能。我们仍是利用上一讲的数据实现, 在"两表查询数据"的工作表中有如下数据:

我们注意到其中型号和生产厂家的数据有些是混的,这就给我们利用上讲的内容造成了不便,那么这个时候就要利用模糊查找了,如下的数据:

我们需要在"两表查询数据"中A列+B列的内容中找到上述表格中A列的对应的型号,怎么处理呢?
我们看下面的代码:
Sub mynzexcels_8()
'第39讲,利用ADO,实现模糊查询
Dim cnADO, rsADO As Object
Dim strPath, strTable, strSQL As String
Set cnADO = CreateObject("ADODB.Connection")
Sheets("Sheet5").Activate
'建立一个ADO的连接
strPath = ThisWorkbook.FullName
cnADO.Open "provider=Microsoft.ACE.OLEDB.12.0;extended properties='excel 8.0;hdr=no;imex=1';data source=" & strPath
i = 2
Do While Cells(i, 1) <> ""
Cells(i, 1).Select
Cells(i, 3) = "": Cells(i, 4) = "": Cells(i, 5) = ""
'这里只是提出F3,F3,F5的数据
strSQL = "select F3,F4,F5 from [两表查询数据$] where F1&F2 Like '%" & Cells(i, 1) & "%'"
Set rsADO = New ADODB.Recordset
rsADO.Open strSQL, cnADO, 1, 3
If rsADO.RecordCount <= 0 Then
MsgBox ("第" & i & "行数据,没有找到!")
Else
If rsADO.RecordCount = 1 Then
Cells(i, 3).CopyFromRecordset rsADO
Else
For TT = 1 To rsADO.RecordCount - 1
Rows(i + TT & ":" & i + TT).Select
Selection.Insert Shift:=xlDown, CopyOrigin:=xlFormatFromLeftOrAbove
Cells(i + TT, 1) = Cells(i + TT - 1, 1): Cells(i + TT, 2) = Cells(i + TT - 1, 2)
Next
Cells(i, 3).CopyFromRecordset rsADO
i = i + TT - 1
End If
End If
rsADO.Close
Set rsADO = Nothing
i = i + 1
Loop
Set cnADO = Nothing
End Sub
代码截图:

代码讲解:
1 strSQL = "select F3,F4,F5 from [两表查询数据$] where F1&F2 Like '%" & Cells(i, 1) & "%'" 这句SQL语句就是实现了从"两表查询数据"的工作表数据中找到类似于Cells(i, 1)内容的记录,大家要注意的这种SQL语句的写法,是like +% %的组合。
2 If rsADO.RecordCount = 1 Then
Cells(i, 3).CopyFromRecordset rsADO
如果仅为1条记录,那么就直接拷贝。
3 For TT = 1 To rsADO.RecordCount - 1
Rows(i + TT & ":" & i + TT).Select
Selection.Insert Shift:=xlDown, CopyOrigin:=xlFormatFromLeftOrAbove
Cells(i + TT, 1) = Cells(i + TT - 1, 1): Cells(i + TT, 2) = Cells(i + TT - 1, 2)
Next
Cells(i, 3).CopyFromRecordset rsADO
i = i + TT - 1
End If
如果是多条记录,那么需要在原查询记录的下面插入行来填入查询的结果,上述代码就是完成了这个目的。
下面我们看代码的运行结果:

今日内容回向:
1 ADO如何实现模糊查找?
2 上述讲解中的SQL语句是否明白呢?