如何用EXCEL VBA编写模糊查询程序,并将结果显示在工作表中

需要模糊查询的内容与目标不完全一致,如要查“角铁 50*5",但系统中有“角铁 40*4” ,此时仍可搜索到。搜索到的多个目标,可以多行显示在工作表中。
有点难,拜求各位大虾了~

不难实现,但代码就懒得写了。
步骤:
1、利用INPUTBOX()获得想查询的内容,并存放到局部变量INPUTDATA 中
2、用DIM MYRANGE AS RANGE 和以下语句组合进行查找
Set MyRange = Sheets("工作表名称").Cells.Find(what:=INPUTDATA, After:=ActiveCell, LookIn:=xlValues, lookat:=xlPart, searchorder:=xlByRows, searchdirection:=xlNext, MatchCase:=False)
3、用条件语句进行判断是否找到或符合
If MyRange Is Nothing Then
MsgBox "没找到符合条件的记录!"
.....
else
找到的话,进行相应的单元格赋值操作
.....
endif
4、用将上述步骤嵌套到一个循环语句内,以便继续查找。
温馨提示:答案为网友推荐,仅供参考
第1个回答  2011-12-19
EXCEL本身就有自动筛选功能,通过自定义筛选条件,就可以实现模糊查找,比如设置筛选条件为“包含”字符“角铁”,就可以把所有“角铁”的项都查询出来!
第2个回答  2011-12-23
建立一个宏或一个按键复制下列代码到里面。
'搜索到的多个目标,可以多行显示在工作表中。
With Cells
Set c = .Find("角铁", LookIn:=xlValues)
If Not c Is Nothing Then
firstAddress = c.Address
Do
r = c.Row
Rows(r).Interior.ColorIndex = 3 '如果存在就把当它所在的行全为红色
Set c = .FindNext(c)
Loop While Not c Is Nothing And c.Address <> firstAddress
End If
End With
第3个回答  2011-12-20
以下代码使用正则表达式,查找 sheet表中a1:b10范围内的值。
Sub 宏2()
'
' 宏2 宏
'
Dim my As String
my = "角铁 \d+\*\d+"
Dim reg
Set reg = CreateObject("VBSCRIPT.REGEXP")
With reg
.Global = True
.IgnoreCase = True
.Pattern = my
End With
Dim iii
iii = 1
Sheets("Sheet1").Select
For Each c In Worksheets("Sheet1").Range("A1:b10")
c.Select
Dim mc As MatchCollection
Dim m As Match
Set mc = reg.Execute(c.Value)
If mc.Count > 0 Then
Worksheets("Sheet2").Cells(iii, 1).Value = c.AddressLocal(RowAbsolute:=False, ColumnAbsolute:=False)
iii = iii + 1
End If
Next c
End Sub

==========================================
欢迎到Excel Home论坛学习、交流
相似回答