通过工作表键入不匹配错误VBA循环

我不断得到一个types不匹配的错误,并试图改变几次types。 我只是试图遍历每个工作表和一个指定的范围,看看这个单词是否存在于该范围的每个单元格中。

Sub CheckWord() Dim arrVar As Variant Dim ws As Worksheet Dim strCheck As Range Set arrVar = ActiveWorkbook.Worksheets 'MsgBox (arrVar) For Each ws In arrVar If ws.Range("C9:G20").Value = "Word" Then MsgBox (True) End If Next ws End Sub 

当你有一个多列的range ,它创build一个数组。 考虑这样的arrays:

 Sub CheckWord() Dim arrVar As Variant Dim ws As Worksheet Dim strCheck As Range Set arrVar = ActiveWorkbook.Worksheets 'MsgBox (arrVar) For Each ws In arrVar For each col in ws.Range("C9:G20").Cells if col.Value = "Word" Then MsgBox (True) end if End If Next ws End Sub 

您无法获取ws.Range("C9:G20")value并将其与一个string进行比较。 你已经select了多个单元格。 如果你想返回True时,如果其中一个单元格包含“单词”,或者当他们都包含“单词”,你需要遍历它们。

这是如何返回您的范围是否包含至less一次任何地方的“Word”的例子

 Function CheckWord() Dim arrVar As Variant Dim ws As Worksheet Set arrVar = ActiveWorkbook.Worksheets For Each ws In arrVar Dim c For Each c In ws.Range("C9:G20").Cells If c = "Word" Then CheckWord = True Exit Function End If Next c Next ws End Function 
 Sub CheckWord() Dim ws As Worksheet For Each ws In ActiveWorkbook.Worksheets If Not ws.Range("C9:G20").Find(What:="Word", LookIn:=xlValues, LookAt:=xlWhole, MatchCase:=False) Is Nothing Then MsgBox "Found in " & ws.Name Next ws End Sub