Calling an opened workbook in VBA - excel

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 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.

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

Related

Trying to Copy Workbook data but when Source opens nothing happens

I'm using the following code:
Dim sourceBook As Workbook
Dim targetBook As Workbook
'## Open both workbooks first:
Set targetBook = Application.ActiveWorkbook
Set sourceBook = Application.Workbooks.Open("...\Documents\Log.xlsm")
'
With sourceBook.Sheets("Sheet1").UsedRange
'Now, paste to y worksheet:
targetBook.Sheets("Sheet1").Range("A1").Resize( _
.Rows.Count, .Columns.Count) = .Value
End With
'Close
sourceBook.Close
But when i run it my source book opens and nothing happens after. Not sure what i'm missing. Both workbooks have the same extension xlsm. Ive tried to change the source to xlsx also but Same result
Edit: Ive replaced the with statement with the following:
targetBook.Sheets("Sheet1").Range("A1").Value = sourceBook.Sheets("Sheet1").Range("A1")
to at least see if i can copy 1 value but when the sourcebook is opened it stops there.
I have recreated your example, and think it is do with the way you are opening the document. In your open method you have three dots Open("...\documents")
It raised an error for me, so can you check that is what you meant? It worked if I used ..\ rather than ...\

VBA - Opening a workbook and remembering it for other macros

I'd like to create a macro that will:
Open a browser window to select a saved workbook (let's call it WB1)
In the same macro assign WB1 some form of reference that will allow it to be referenced by other macros
I can achieve step 1 via the following code:
Sub Add_New_Survey()
Dim pathString As String
Dim resultWorkbook As Workbook
Dim found As Boolean
pathString = Application.GetOpenFilename(fileFilter:="All Files (* . xl*) , *.xl* ")
' check if it's already opened
For Each wb In Workbooks
If InStr(pathString, wb.Name) > 0 Then
Set resultWorkbook = wb
found = True
Exit For
End If
Next wb
If Not found Then
Set resultWorkbook = Workbooks.Open(pathString)
End If
End Sub
This will open the workbook. I then need to perform a number of data preparation activities on WB1 which I would like to automate. Is there a way to reference WB1 as I open it from the browser so the following macros know to look on WB1 specifically?
Many thanks
Welcome to SO. Your object resultWorkbook is linked to Workbooks.Open(pathString), so as long as you dont unlink it with Set resultWorkbook = Nothing, you can reference that workbook always on any sub, (but declare the variable as Public first in the module, outside of all subs).
To declare a Variable as Public, please read:
How do I declare a global variable in VBA?

Excel VBA remove unwanted worksheets

I have MS Access producing a bunch of workbooks and worksheets. When a workbook is creates there are extra worksheets in the workbook named "Sheetn"
I know the following code works but my question is about timing.
Dim ws as excel.worksheet
For each ws in wbWorking.Worksheets
oxl.DisplayWarnings=False
If ws.name like "Sheet*" then ws.delete
oxl.DisplayWarnings=True
Next ws
The above code does not work until I save the Workbook. The issues is that the client is watching for the workbooks to populate the directory and will open them as soon as they show. This causes issues if the above code runs and the client has the workbook open. I would like to delete worksheets before the workbook is saved.
Please advise.
Working from when you first create the new workbook, something along these lines should work:
Public Function BuildWorkbook(wbkToCopy As Excel.Workbook) As Excel.Workbook
Dim xl As Excel.Application
Dim dummySheet As Excel.Worksheet
Dim sheetToClone As Excel.Worksheet
Dim i As Long
Set xl = wbkToCopy.Application
Set BuildWorkbook = xl.Workbooks.Add(1)
Set dummySheet = BuildWorkbook.Worksheets(1)
For Each sheetToClone In wbkToCopy.Worksheets
'This is just to handle naming conflicts
Do Until sheetToClone.Name <> dummySheet.Name
dummySheet.Name = Format(Now(), "yyyymmddhhnnss") & CStr(i)
i = i + 1
DoEvents
Loop
sheetToClone.Copy BuildWorkbook.Worksheets(1)
Next
If BuildWorkbook.Worksheets.Count > 1 Then
dummySheet.Delete
End If
End Function
Obviously, you can add the sheets however you need to, but the keys are:
Specify =Workbooks.Add(1) when you create the new workbook, so it is created with only 1 worksheet
Set a reference to the worksheet that you don't want when you first create the new workbook
Using that initial reference, delete the worksheet at the very end of the process, before saving the workbook

How to reference an opened not active workbook?

I want to reference from code in an active workbook to another workbook,
I don't want to type path like that workbooks("path") , this reference should be flexible, is there something like array of already opened workbooks ?
You can assign an open workbook to a variable without providing the full path. You can then use the set object variable to perform any actions you wish.
Sub set_wb()
Dim wb As Workbook
Set wb = Workbooks("test_wb.xlsb")
wb.Activate
End Sub
You can also iterate through each open workbook using for each
Sub wb_names()
Dim wb As Workbook
For Each wb In Workbooks
Debug.Print wb.Name
Next wb
End Sub
Similarly, you can use for to iterate through each workbook using their index (the index is dependant on which order workbooks were opened).
Sub wb_index()
Dim i As Byte
For i = 1 To Workbooks.Count
Debug.Print Workbooks(i).Name
Next i
End Sub
Hope this helps.
See this answer.
To reference an already open workbook, you can use
Workbooks("book_name.xlsx")
You can also iterate through the collection
Dim i As Integer
For i = 1 To Workbooks.Count
MsgBox Workbooks(i).Name
Next i

run time error 1004 in opening two different workbooks

I am trying to open two different workbooks for transferring data. The complete location of workbooks are in two cells of the current workbook. First workbook opens correctly but there is error in opening other workbook. It says:
run time error 1004. File can't be found.
However, if i use path of workbook directly in the code, then it works fine. Anybody please tell me what I am doing wrong.
Sub ProcessReport()
Dim MainWb As Workbook
Dim DestWb As Workbook
' Load source and destination files
Set DestWb = Workbooks.Open(Range("E10").Value)
Set MainWb = Workbooks.Open(Range("E6").Value)
' Code for manipulation
End Sub
In your original code the second workbooks.open command is reading the cell "E6" from the workbook "DestWb" because that is the activeWorkbook at the time that command is executed, rather than the workbook where the macro is saved.
You can fix this by changing:
Set DestWb = Workbooks.Open(Range("E10").Value)
Set MainWb = Workbooks.Open(Range("E6").Value)
To this:
Set Ws = ThisWorkbook.Sheets("Sheet1")
Set DestWb = Workbooks.Open(Ws.Range("E10").Value)
Set MainWb = Workbooks.Open(Ws.Range("E6").Value)
This will save "Sheet1" from the workbook where the macro is running as an object reference so that your macro tries to use the filepaths in "E10" and "E16" from the workbook where the macro is saved. Range("E6").Value is now qualified with the worksheet ws.
You can change "Sheet1" to whatever the tab is where the filepaths are in your macro workbook.

Resources