簡體   English   中英

運行時錯誤#13-類型不匹配(如果范圍…則…)

[英]Run time error #13 - type mismatch (if range … then …)

我需要掃描一定范圍內的某些單元格。 如果某些單元格為空,則消息“單元格為空”將被寫入該特定的空單元格中。 我一直在嘗試以下方法:

    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

您會收到錯誤13,因為在包含多個單元格的Range上調用.Value返回Variant數組。 您不能使用這樣的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的Sub-這是一個保留關鍵字。

確定存在一個或多個空白單元格后,將Range.SpecialCells方法xlCellTypeBlanks屬性一起使用。

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

空和IsEmpty是VBA中的保留字。 通常最好是最好避免使用它們。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM