尝试在VBA中向脚本添加范围时出现运行时错误1004

时间:2014-03-13 18:16:10

标签: vba excel-vba excel

下面的脚本适用于单个单元格,但当我尝试添加范围Q3:Q200时,它会抛出Runtime Error 1004

VBA脚本:

Private Sub Workbook_BeforeSave(ByVal SaveAsUI As _
            Boolean, Cancel As Boolean)
    With Sheets("  Sheet3  ").Range("  Q3  ")
        If .Value = "  Shirts  " Then
            If Range("  R3  ") = "" Then
                MsgBox "  Save has been cancelled. You must fill Type of Shirts  "
                Cancel = True
            End If
        End If
    End With
End Sub

1 个答案:

答案 0 :(得分:0)

您需要遍历该范围才能找到"衬衫"的值。试试这个:

Private Sub Workbook_BeforeSave(ByVal SaveAsUI As Boolean, Cancel As Boolean)
    Dim c As Range
    For Each c In Range("Sheet3!Q3:Q200")
    Debug.Print c.Address & "  " & c.Value
        If c.Value = "Shirts" Then
            If c.Offset(0, 1).Value = "" Then
                MsgBox "Save has been cancelled. You must fill Type of Shirts"
                Cancel = True
                Exit Sub
            End If
        End If
    Next
End Sub

或者,您可以使用Range("Sheets3!Q3:Q200").Find("Shirts"),但我认为这实际上需要更多代码。