【问题标题】:Run time error #13 - type mismatch (if range ... then ...)运行时错误 #13 - 类型不匹配(如果范围 ... 那么 ...)
【发布时间】:2016-11-05 12:37:52
【问题描述】:

我需要扫描某个范围内的某些单元格。如果某些单元格为空,则消息“单元格为空”将写入该特定的空单元格中。我一直在尝试以下方法:

    Sub Empty()

       Sheets("My sheet").Select
       If Range("C5:C12,C15:C22,C25:C32,C36:C43,C46:C53,C56:C63,C66:C73,C76:C83,D4,D14,D24,D35,D45,D55,D65,D75").Value = "" Then
          Range("C5:C12,C15:C22,C25:C32,C36:C43,C46:C53,C56:C63,C66:C73,C76:C83,D4,D14,D24,D35,D45,D55,D65,D75").Value = "cell is empty"
       End If
    End sub

I am getting the error: run time error #13 - type mismatch. 

为了帮助可能遇到与我相同问题的任何其他人,我将补充下面介绍的工作解决方案。请注意,我添加了一个错误处理来阻止消息“运行时错误 '1004': No Cells were found" 以及一个用于扫描符合您需求的特定工作表的数组:

    Sub myEmpty()
        Dim rng As Range
        On Error GoTo NoBlanks   
        Dim MyArray As Worksheet

        For Each MyArray In ActiveWorkbook.Worksheets
          Select Case MyArray.Name
            Case Is = "Sheet 1", "Sheet 2", "Sheet 3", "Sheet n-1", "Sheet n"

            With MyArray
            Set rng = .Range("C5:C12,C15:C22,C25:C32,C36:C43,C46:C53,C56:C63,C66:C73,C76:C83,D4,D14,D24,D35,D45,D55,D65,D75")
              If CBool(Application.CountBlank(rng)) Then
                rng.SpecialCells(xlCellTypeBlanks).Value = "cell is empty"
              End If
            End With

          Case Else
          End Select
          Next MyArray

NoBlanks:

 CreateObject("WScript.Shell").Popup "   There are no empty cells", 0.7, "INfo:"

End Sub

【问题讨论】:

    标签: vba excel error-handling


    【解决方案1】:

    在确定有一个或多个空白单元格后,使用Range.SpecialCells methodxlCellTypeBlanks 属性。

    Sub myEmpty()
        dim rng as range
        with Sheets("My sheet")
            set rng = .Range("C5:C12,C15:C22,C25:C32,C36:C43,C46:C53,C56:C63,C66:C73,C76:C83,D4,D14,D24,D35,D45,D55,D65,D75")
            If cbool(application.countblank(rng)) then
                rng.specialcells(xlCellTypeBlanks).Value = "cell is empty"
            End If
        end with
    End sub
    

    Empty 和 IsEmpty 是 VBA 中的保留字。通常最好避免重新利用它们。

    【讨论】:

      【解决方案2】:

      您收到错误 13,因为在包含多个单元格的 Range 上调用 .Value 会返回 Variant 数组。您也不能使用这样的 If 语句将一个条件应用于 Range 中的多个单元格 - 您需要使用循环并测试单个单元格:

      Public Sub FlagEmptyCells()
          Dim target As Range
          Set target = Range("C5:C12,C15:C22,C25:C32,C36:C43,C46:C53,C56:C63,C66:C73,C76:C83,D4,D14,D24,D35,D45,D55,D65,D75")
      
          Dim current As Range
          For Each current In target
              If current.Value = vbNullString Then current.Value = "cell is empty"
          Next
      End Sub
      

      另请注意,您不能有一个名为 Empty 的 Sub - 它是一个保留关键字。

      【讨论】:

      • 共产国际,您的解决方案也是一个不错的选择。感谢您的宝贵时间!
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-10-28
      相关资源
      最近更新 更多