开发者

worksheet.activate isn't activating

开发者 https://www.devze.com 2023-01-24 09:13 出处:网络
The code snippet below is intended to open a specific worksheet of a specific XL file and make it the active worksheet.However, the debug.print gives an output of different sheets.Shouldn\'t objws.act

The code snippet below is intended to open a specific worksheet of a specific XL file and make it the active worksheet. However, the debug.print gives an output of different sheets. Shouldn't objws.activate make objws the active worksheet?

Dim XLApp As New Excel.Application
Dim ObjXL As Excel.Workbook
Dim ObjWS As Excel.Worksheet

S开发者_运维技巧et ObjXL = XLApp.Workbooks.Open(TargetXL)
Set ObjWS = ObjXL.Worksheets(TargetWS)
ObjWS.Activate
Debug.Print ObjWS.Application.ActiveSheet.Name & "," & ObjWS.Name


Your debug line is printing the name of the active sheet of the application, which may be a sheet in a workbook other than the workbook you have just opened. If you activate that workbook first, then the application's active sheet should become the sheet in that workbook. I.e.

Dim XLApp As New Excel.Application
Dim ObjXL As Excel.Workbook
Dim ObjWS As Excel.Worksheet

Set ObjXL = XLApp.Workbooks.Open(TargetXL)
Set ObjWS = ObjXL.Worksheets(TargetWS)
ObjXL.Activate ' add this line
ObjWS.Activate
Debug.Print ObjWS.Application.ActiveSheet.Name & "," & ObjWS.Name

You may also want consider whether you really need to activate the worksheet. If the user specifically needs to be viewing the sheet after your VBA has run, then this is a valid reason. If however, you only need to act on the sheet in your code, then you can just reference all it's properties by using the ObjWS variable without actually activating it.


Try Select() instead.

0

精彩评论

暂无评论...
验证码 换一张
取 消