我是VBA的新手,正在尝试将一些代码拼凑在一起,以允许用户在一个单元格中输入一个单词(或几个单词),然后显示匹配的行条目的列表。
我尝试了以下代码,但收到“ instring = type mismatch
”错误。
请注意,“ B3
”是用于“搜索词”的字段,而列F
是包含要在其中搜索文本的列。如果包含该单词,我想显示该行并隐藏所有不包含该单词的行。
Sub Find_Possible_Task()
ROW_NUMBER = 0
SEARCH_STRING = Sheets("codeset").Range("B3")
ROW_NUMBER = ROW_NUMBER + 1
ITEM_IN_REVIEW = Sheets("codeset").Range("F:F")
If InStr(ITEM_IN_REVIEW, SEARCH_STRING) Then
Do
Cells(c.Row).EntireRow.Hidden = False
Loop Until ITEM_IN_REVIEW = ""
End If
End Sub
TIA!
答案 0 :(得分:0)
考虑使用range.find()代替instr()。
Sub Find_Possible_Task()
Dim SEARCH_STRING As String
Dim ITEM_IN_REVIEW As Range
Dim found As Range
Dim i As Integer
SEARCH_STRING = Sheets("Sheet1").Range("B3").Value
i = 1
Do
Set ITEM_IN_REVIEW = Sheets("Sheet1").Cells(i, 6)
Set found = ITEM_IN_REVIEW.Find(What:=SEARCH_STRING)
If found Is Nothing Then
ITEM_IN_REVIEW.EntireRow.Hidden = True
End If
i = i + 1
Loop Until ITEM_IN_REVIEW = ""
End Sub
或者,考虑使用过滤器表: 1.检查您的表是否在==>上有过滤器,如果是,则通过。如果否,请打开过滤器。 2.过滤F列以使关键字包含单元格B3中的值。
答案 1 :(得分:0)
很少有错误的编码约定,甚至可能是彻头彻尾的错误:
Public/Private
过程的范围Sub
Dim
关键字声明它们Option Explicit
将有助于您防止上述错误(主观)变量很难看,在大多数编程语言中,习惯上将所有大写字母的变量名保留为常量(Const
)
Option Explicit
Private Sub keep_matches()
Dim what As Range
Dim where As Range
Dim res As Range ' result
Dim lr As Long ' last active row
Dim ws As Worksheet: Set ws = Sheets("codeset")
lr = ws.Cells(ws.Rows.Count, "F").End(xlUp).Row
Set what = ws.Range("B3")
Set where = ws.Range("F1:F" & lr)
' we'll create an extra column for a loop in our .Find method
where.Copy
ws.Range("F1").EntireColumn.Insert
ws.Range("F1").PasteSpecial xlPasteValues
where.EntireRow.Hidden = True ' preemptively hide them all
Set where = ws.Range("F1:F" & lr)
Set res = where.Find(what, lookIn:=xlValues) ' ilook for matches, 1st attempt
If Not res Is Nothing Then ' if found
Do Until res Is Nothing ' repeat for all results
res.EntireRow.Hidden = False
res = "Checked"
Set res = where.FindNext(res)
Loop
Else
MsgBox("No matches were found")
where.EntireRow.Hidden = False ' we don't wanna hide anything
End If
ws.Range("F1").EntireColumn.Delete ' remove the extra help column for Find method
End Sub
应能按预期工作。
如有任何疑问,请告诉我。