类型不匹配错误VBA循环通过工作表

时间:2016-08-03 18:08:58

标签: excel vba excel-vba

我一直遇到类型不匹配错误,并尝试更改类型几次。我只是试图遍历每个工作表和指定的范围,以查看该范围的每个单元格中是否存在该单词。

<div class="container-fluid">

  <div class="row">
    <div class="col-md-7">
      <img src="http://placehold.it/550x350" class="img-responsive" style="width:100%" alt="Image">
    </div>
    <div class="col-md-5">
      <h2>How do you auto-resize a large image so that it will fit into a smaller width div container whilst maintaining it's width:height ratio?</h2>
    <p>How do you auto-resize a large image so that it will fit into a smaller width div container whilst maintaining it's width:height ratio?</p>
    </div>
  </div>
</div>

3 个答案:

答案 0 :(得分:1)

您无法获得value ws.Range("C9:G20")并将其与一个字符串进行比较。您已选择多个单元格。如果你想在其中一个单元格包含&#34; Word&#34;时返回True。或者当所有这些都包含&#34; Word&#34;你需要迭代它们。

这是一个如何返回您的范围是否包含&#34; Word&#34;任何地方至少一次

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

答案 1 :(得分:1)

如果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
   For each col in ws.Range("C9:G20").Cells
      if col.Value = "Word" Then
         MsgBox (True)
      end if
   End If
Next ws

End Sub

答案 2 :(得分:0)

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