运行时错误#13 - 类型不匹配(如果范围...则......)

时间:2016-07-03 19:20:59

标签: excel vba excel-vba error-handling

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

    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':找不到单元格“以及用于扫描符合您需求的特定工作表的数组:

    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

2 个答案:

答案 0 :(得分:2)

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

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的子广告 - 它是一个保留关键字。

答案 1 :(得分:2)

在确定有一个或多个空白单元格后,使用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中的保留字。通常最好避免重复使用。