简体   繁体   中英

Activate Excel sheet in VBA without navigating to the worksheet

是否可以从VBA激活Excel工作表而无需实际离开启动宏的工作表?

Yes you can directly run the desired code in the New Worksheet by using the with command

With Sheets("Sheet2") 'Sheet2 is the new sheet
    Debug.Print .Range("A1")
    'Run your desired code here.
End With

Yes.

ThisWorkbook.Worksheets(2).Activate

This will make the desired worksheet be set as active. Note that if you do not disable Application.ScreenUpdating first, as mentioned in the other answer here, the worksheets will visibly jump around so that the active worksheet is being displayed.

However, I must ask, why do you need to activate the worksheet? If you want to run some commands against cells located on that worksheet, you can do so without activating the worksheet first:

Dim ws As Worksheet
Set ws = ThisWorkbook.Worksheets(2)

ws.Range("A1").Value = "Hello world"

This snippet will insert "Hello world" into the cell A1 on the second worksheet in your workbook - no worksheet activation required.

You can set Application.ScreenUpdating property to false ,and after your work is done, recover it to true .
Refer to the example: https://msdn.microsoft.com/en-us/library/office/ff193498.aspx

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