简体   繁体   中英

Excel Macro vs Excel Add-In and cell selection

I am trying to determine why "Cells.Select" (which is used to select all the cells in a worksheet) will work in a macro but the exact same command will result in a Run-time error: 1004. Has the add-in been set up in correctly? Is there a difference in how the code is executed between running a macro vs running an add-in?

This also will apply to any command using "Cells" such as the following...

If Not IsEmpty(Cells(a, 1)) Then

    Cells(a, 3) = Num

End If

Note that the value of Num is a valid integer but the point I'm trying to make here is that the actual cell value is not set to Num when the condition is TRUE.

Thank you in advance

Using your example and the extra info you've provided in the comments section, your code of:

If Not IsEmpty(Cells(a, 1)) Then

    Cells(a, 3) = Num

End If

Would better be:

With Application.ActiveSheet

    If Not IsEmpty(.Cells(a, 1)) Then

        .Cells(a, 3) = Num

    End If

End With

Also, try to resist using .Select unless you really have to. Check out: this excellent article

ThisWorkbook will directly reference the workbook that the code resides in. It is possible to have a hidden worksheet as part of an Addin having done it myself and that is the only reason to ever use ThisWorkbook in an Addin.

With an Addin you most always want to make reference to ActiveWorkbook to apply macros to whatever workbook the Addin needs to manipulate. Also use ActiveSheet where referencing sheets too.

Change your code to ActiveSheet.Cells.Select

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