简体   繁体   English

类型不匹配错误VBA遍历工作表

[英]Type mismatch error VBA loop through worksheets

I keep getting a type mismatch error and have tried changing the type a few times. 我不断收到类型不匹配错误,并尝试过几次更改类型。 I'm just trying to loop through each worksheet and a specified range to see if that word exists in every cell of that range. 我只是试图遍历每个工作表和指定的范围,以查看该单词在该范围的每个单元格中是否存在。

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

You can't get the value of ws.Range("C9:G20") and compare it to one string. 您无法获取ws.Range("C9:G20")value并将其与一个字符串进行比较。 You've selected multiple cells. 您选择了多个单元格。 If you want to return True when nay one of these cells contains "Word" or when all of them contain "Word" you'll need to iterate over them. 如果不想在其中一个单元格包含“ Word”时或在所有单元格都包含“ Word”时返回True ,则需要对它们进行迭代。

This is an example of how to return whether or not your range contains "Word" anywhere at least once 这是一个如何至少一次返回范围是否包含“ 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

When you have a range with many columns, it creates an array. 当您有一个包含许多列的range时,它将创建一个数组。 Taking the array into consideration like so: 像这样考虑数组:

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
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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM