简体   繁体   中英

Calling an opened workbook in VBA

this is what i currently have,

Dim mastertemp As Workbook
Dim testproject As Workbook

Set testproject = Workbooks("C:\Users\zzz\Documents\Test Project.xlsm")
Set mastertemp = Workbooks("C:\Users\zzz\Documents\MasterTemp.xlsx")

mastersheet.sheets("Sheet1").activate

the third line of code is giving me subscript out of range, any ideas?

I want to be able to jump between workbooks without the system giving me "workbook is already open, reopening would discard all changes etc"

I would do something like this:

Dim wbk as Workbook
Set wbk = Workbooks("Test Project.xlsm")

do stuff
Workbooks.Open ("C:\Users\zzz\Documents\MasterTemp.xlsx")
do stuff

wbk.Sheets("Dashboard").Activate

If you know the workbook is already open, then refer to it by name in the Workbooks collection:

Dim testProject as Workbook
Set testProject = Workbooks("C:\Users\zzz\Documents\Test Project.xlsm")
testProject.Sheets("Dashboard").Activate

If you don't know whether the workbook is open, then you can use some error-handling logic, like:

Dim testProject as Workbook

On Error Resume Next
' Attempt to index this workbook from the open Workbooks collection:
Set testProject = Workbooks("C:\Users\zzz\Documents\Test Project.xlsm")
If Err.Number <> 0 Then
    ' If the above fails, then the workbook isn't open, so we need to open it:
    Set testProject = Workbooks.Open("C:\Users\zzz\Documents\Test Project.xlsm")
End If
On Error GoTo 0

If you will always know the name of your workbook you can do

workbooks("Test Project").sheets("Dashboard").Activate 'add the file extension to the name if you've turned on file extensions in windows explorer 

If the workbook name might be changing (or evening if it isn't, and you'll be referring to the workbook multiple times) then findwindow's suggestion is the way to go.

dim TestWorkbook as workbook
set TestWorkbook=Workbooks.Open ("C:\Users\zzz\Documents\Test Project.xlsm")
TestWorkbook.sheets("Dashboard").activate

I hope this helps.

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