如何使用If语句search特定文本的列?
我试图让代码来检查整个列是否包含特定的文本 。
它永远是首都。 这行后面有很多代码,但是我只希望代码在满足以下条件的情况下运行。 我正在考虑的代码如下。
If ActiveSheet.Range("J:J").Text = "GENERAL" Then
然而,这没有返回,我试过Instr()
但无济于事。
什么是正确的语法?
你可以在一个范围内search;
if not ActiveSheet.Range("J:J").Find("GENERAL", MatchCase:=True) is nothing then msgbox "found it!" end if
FInd
有usuage
Find(What, [After], [LookIn], [LookAt], [SearchOrder], [SearchDirection As XlSearchDirection = xlNext], [MatchCase], [MatchByte], [SearchFormat])
你应该指定匹配“GENERAL”应该是整个string(使用LookAt:=xlWhole
)还是部分匹配(即匹配GENERAL中的GENERAL使用LookAt:=xlPart
)
此外,通常最好使用Range
对象(下面的rng1
),以便您可以使用find的对象。 虽然在你的情况下布尔testing将足以运行或不运行你的进一步的代码
部分匹配
Sub FindPartialString() Dim rng1 As Range 'find partial match Set rng1 = ActiveSheet.Range("J:J").Find("GENERAL", , xlValues, xlPart, , , True) If Not rng1 Is Nothing Then MsgBox "found in " & rng1.Address(0, 0) Else MsgBox "no found", vbCritical End If End Sub
整场比赛
Sub FindWholeString() Dim rng1 As Range 'find exact match Set rng1 = ActiveSheet.Range("J:J").Find("GENERAL", , xlValues, xlWhole, , , True) If Not rng1 Is Nothing Then MsgBox "found in " & rng1.Address(0, 0) Else MsgBox "no found", vbCritical End If End Sub