简体   繁体   中英

VBA: Referencing a Worksheet in the Active Workbook

While this seems very basic, I am continually getting an error message while trying to select a cell in a certain sheet on my workbook in my Macro. Does any one know why this will not work? I'm getting error message Run Time Error '1004'. The sheets name is "Sheet1"and my code is below:

 Application.ActiveWorkbook.Worksheets("Sheet1").Range("N2").Select

It's bad practice to use ActiveWorkbook when you don't need to. It's always better to set your workbooks and worksheets to actual variables that you can call on. I think your code is activating another workbook then trying to select a range in a worksheet it can't find.

Sub TryThis()

    Dim wbk As Workbook
    Dim ws As Worksheet

    Set wbk = Workbooks("myWorkbook.xlsm")
    Set ws = wbk.Worksheets("Sheet1")

    'Now when we say "ws." it is actually "Workbooks("myWorkbook.xlsm").Worksheets("Sheet1")."

    'This is okay to start with but it's better to work with the cells directly
    ws.Select
    Range("N2").Select
    Selection = "myText"

    'This is much faster and you won't have to worry about what is currently selected
    ws.Range("N2") = "myText"

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