VBA - Excel.Range声明上的类型不匹配

时间:2017-11-17 02:47:40

标签: vba excel-vba excel

我正在尝试在excel工作簿的BeforeSave()事件中将一系列单元格声明为Excel.Range变量。 背景是,此范围内的值是强制性输入,我想验证它们是否都在保存时填充。

如果我想执行该功能,我会收到错误消息

Private Sub Workbook_BeforeSave(ByVal SaveAsUI As Boolean, Cancel As Boolean) Dim r1 As Range Set r1 = Range("G11:G14") If Cells(10, 1).Value = "" Then MsgBox "Cell requires user input", vbInformation, "Please filled up the mandatory cells" Cancel = True Exit Sub ElseIf r1.Value = "" Then // runtime error "13": Type Mismatch MsgBox "Please make sure you had filled in all the Questionnire Answers.", vbInformation, "Missing Answer" Cancel = True Exit Sub End If Cancel = False End Sub

这是我试过的代码。

files

我对VBA比较陌生,所以请随意指出我的错误。 提前谢谢!

2 个答案:

答案 0 :(得分:1)

我怀疑它是因为您需要将范围定义限定为Set r1 = ThisWorkbook.Range("G11:G14")。此外,我相信多单元格范围的.Value属性将返回最左上角单元格中的值。

答案 1 :(得分:1)

您将收到此错误:

  

运行时错误“13”:类型不匹配

因为Range被定义为多个单元格的Range,您无法检查多单元格Function是否只是空字符串。您需要检查范围内的每个单元格。

尝试此代码 - 它是"",用于检查一组单元格中的任何单元格是否为True,如果是这样,则返回Option Explicit Function TestMultipleCellsAnyAreEmpty(rng As Range) As Boolean Dim rngCell As Range Dim blnAnyRangeIsEmpty blnAnyRangeIsEmpty = False For Each rngCell In rng If rngCell.Value = "" Then blnRangeIsEmpty = True Exit For End If Next rngCell TestMultipleCellsAreEmpty = blnRangeIsEmpty End Function

Option Explicit

Private Sub Workbook_BeforeSave(ByVal SaveAsUI As Boolean, Cancel As Boolean)
    Dim r1 As Range
    Set r1 = ThisWorkbook.Worksheets("YOUR_SHEET").Range("G11:G14") '<-- specify the worksheet

    If ThisWorkbook.Worksheets("YOUR_SHEET").Cells(10, 1).Value = "" Then '<-- specify the worksheet
        MsgBox "Cell requires user input", vbInformation, "Please filled up the mandatory cells"
        Cancel = True
        Exit Sub
    ElseIf TestMultipleCellsAnyAreEmpty(r1) Then
        MsgBox "Please make sure you had filled in all the Questionnire Answers.", vbInformation, "Missing Answer"
        Cancel = True
        Exit Sub
    End If
    Cancel = False

End Sub

Function TestMultipleCellsAnyAreEmpty(rng As Range) As Boolean

    Dim rngCell As Range
    Dim blnAnyRangeIsEmpty

    blnAnyRangeIsEmpty = False

    For Each rngCell In rng
        If rngCell.Value = "" Then
            blnRangeIsEmpty = True
            Exit For
        End If
    Next rngCell

    TestMultipleCellsAreEmpty = blnRangeIsEmpty

End Function

将此技术与您的工作簿事件相结合,您可以获得完整的代码:

$scope.$apply