简体   繁体   中英

VBA Macro: Application-defined or object-defined error

I'm struggling with the syntax on a VBA macro. Trying to create a select from Sheet 2 list on Sheet 1, and it gives me Run-time error '1004': Application-defined or object-defined error.

Sub Macro1()

Sheets("Sheet1").Select
Sheets("Sheet1").Range("G3").Select
With Selection.Validation
.Add Type:=xlValidateList, AlertStyle:=xlValidAlertStop, Operator:= _
    xlBetween, Formula1:="Sheet2!$A$1:$A$14"
.IgnoreBlank = True
.InCellDropdown = True
End With


End Sub

Please help me understand why I am getting this error and how to fix it?

If you are running the macro more than once, you need to ensure you delete any existing validation

Sub Macro1()
    With Sheets("Sheet1").Range("G3").Validation
        'Remove existing validation
        .Delete
        'Add new validation
        .Add Type:=xlValidateList, _
             AlertStyle:=xlValidAlertStop, _
             Operator:=xlBetween, _
             Formula1:="=Sheet2!$A$1:$A$14"
           'Note - need ^ (i.e. the equals sign to make it a formula)
        .IgnoreBlank = True
        .InCellDropdown = True
    End With
End Sub

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM