Out of range error for Windows().Activate

2020-07-31 03:40发布

I have a bit of code in my macro as follows

ChDir File_pth
Workbooks.Open filename:= File_pth & "\" & open_tkt
Workbooks.Open filename:= File_pth & "\" & closed_tkt
ActiveSheet.Select
Windows("MSS - Ticket Backlog Benchmark_2013 09 05.xlsx").Activate
Sheets("Extract -prev").Select

When I run the macro to open two other files, it should go back to the file in which I run macro to do some operations in the same Xl workbook.

I get the out of range error in the line

Windows("MSS - Ticket Backlog Benchmark_2013 09 05.xlsx").Activate

The file MSS - Ticket Backlog Benchmark_2013 09 05.xlsx exists.

标签: excel vba
3条回答
相关推荐>>
2楼-- · 2020-07-31 03:51

You must place your macros in modules instead of in "This Workbook" or in specific sheets. Otherwise, you will have that window interaction problem. I had the very same issue and that's how I solved it.

Like this:

查看更多
来,给爷笑一个
3楼-- · 2020-07-31 04:02

try

windows("MSS - Ticket Backlog Benchmark_2013 09 05").Activate

you could check the names of all open workbooks in Debug window like this:

dim oBook as workbook

for each obook in workbooks
    debug.print ">" & obook.name & "<"
next
查看更多
等我变得足够好
4楼-- · 2020-07-31 04:04

Activating the original sheet should bring the original window to the front too, so you shouldn't need to play with the windows. (works for me anyway)

Dim Book As Workbook ' probably not needed
Set Book = ThisWorkbook ' probably not needed
Dim Sheet As Worksheet
Set Sheet = ActiveSheet
ChDir File_pth
Workbooks.Open filename:= File_pth & "\" & open_tkt
Workbooks.Open filename:= File_pth & "\" & closed_tkt
Book.Activate() ' probably not needed
Sheet.Activate()

I've added code to activate the original workbook before activating the original sheet (lines with the comments at the end) and as it says, they are probably not needed.

The variables Book and Sheet are references to The active workbook (ThisWorkbook) and the active sheet (ActiveSheet). This is what @mehow was suggesting.

查看更多
登录 后发表回答