运行时错误#13 – types不匹配(如果范围…则…)

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

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. 

为了帮助其他可能与我有同样问题的人士, 我将补充下面提供的工作解决scheme。 请注意,我添加了一个error handling,防止消息“运行时错误'1004':没有find单元”,也是一个数组来扫描符合您的需求的特定工作表:

  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 

确定有一个或多个空白单元格后,使用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 

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

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

 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 – 这是一个保留关键字。