Excel VBA Code to select opened Excel file - vba

I've done lots of search through various website but to no avail.
Previously I create simple VBA to select XLS from automatic-generated-XLS which created by a software as below. This excel does not have any file type at it's end because it was not saved anywhere yet and i'm not planning to save it.
Sub Test()
Windows("All Jobs").Activate
End Sub
Lately, the software generate new file name "All Jobs (0 - XX)" which XX could be any number from 1 to 100. So, the code above does not work anymore. Adding * does not help.
Any suggestion?
Thanks in advance.
Zaiem

You can loop thru the Windows collection to check the caption of each window. Try this:
Private Sub Test()
Dim myWindow As Window
For Each myWindow In Windows
If Left(myWindow.Caption, 8) = "All Jobs" Then myWindow.Activate: Exit Sub
Next myWindow
End Sub

You can loop through all Workbooks in Application (Excel), and if the current workbook's name is Like "All Jobs" & "*" >> this is your desired workbook.
Note: verify that you need to Activate the workbook, usually it is not needed.
Code
Option Explicit
Sub Test()
Dim WB As Workbook
Dim AllJobSWB As Workbook
For Each WB In Application.Workbooks
If WB.Name Like "All Jobs" & "*" Then
Set AllJobSWB = WB ' set the matched workbook
Exit For
End If
Next WB
' if you must activate the workbook, use the line below
AllJobSWB.Activate
End Sub

Related

how can i retrieve a list of currently open workbooks and get VBA to put them in a mulitple choice dialouge box?

Good morning. so in essence i have built a whole bunch of macros that work fine after a lot of work. trouble i have is the macros will always need to perform actions on other workbooks ie: "macro workbook" contains macros that perform actions on "January 2018 data". The reason for this is that the monthly data sheets are always new so i cant store macros on them.
i personally and happy to open a separate workbook, press f11 and run the correct macro. there may be end users in the future however that are not comfortable with this and so i want to employ the use of a button. obviously by implementing a button on the "macro workbook", it applies the macros function to the macro workbook, not the intended one.
In an ideal world i want to press the macro button and be presented with a list of currently opened workbooks that the user can read through and select the correct workbook. it will then select this open workbook and then continue with the macro.
Is this even possible? I'm new to VBA but i have never come across this before. the closest fix i can think of is to ask the user to input the file directory and name in a dialogue box, then use that to select the workbook to continue running the macro, such as:
Sub macro1()
Dim Filepath As String
Filepath = InputBox("Please enter the filename of workbook you wish to run the macro on", "Enter Filepath")
Workbooks(Filepath).Activate
rest of macro can then continue...
End Sub
I would just rather the user be able to click the name of the workbook rather than have to input it, to reduce the chance of them inputting it wrong.
There are so many ways that this could be implemented. Here is a very simple way which might give you at least one idea. In your main workbook with "your macros" … create UserForm with a Combobox and a Button on it … like the following:
Add the following code in the UserForm:
Option Explicit
Private Sub UserForm_Activate()
Dim vWorkbook As Workbook
ComboBox1.Clear
For Each vWorkbook In Workbooks
ComboBox1.AddItem vWorkbook.Name
Next
End Sub
Private Sub CommandButton1_Click()
If ComboBox1.ListIndex <> -1 Then
Call YourMacro(ComboBox1)
End If
End Sub
Private Sub YourMacro(vWorkbookName As String)
MsgBox Workbooks(vWorkbookName).Name
End Sub
Then create a module so that when you bring up the macro dialog box there a macro to load the form.
Option Explicit
Public Sub LoadForm()
UserForm1.Show
End Sub
When the form is activated, the code loads the names of the currently open workbooks into the ComboBox. You can select one. Click the button … and after it checks that a workbook has been selected, it runs an example macro which is mimicking your own macro (which in this example displays the workbook name by referencing the Workbooks object). Because clearly in "your" macros … they should be reference the selected Workbook.
Once again … clearly this is very rudimentary. Its intended to one example of what's possible and might point you in the right direction.
Another method, this will DO_THIS_MACRO on the also open workbook, if there is only 1 other workbook open. If there are 2 or more, will cycle through them asking if you want to DO_THIS_MACRO on that workbook, or go to next, or Cancel.
Sub DoOnOpenWorkbooks()
'Define a Workbook Object
Dim oWb As Workbook, iSh As Worksheet, WkbCount As Double, numa As Integer
'Traverse through each workbook Opened - Using Excel Application Object
WkbCount = 0
For Each oWb In Application.Workbooks
WkbCount = WkbCount + 1
Next oWb
' Do not list PERSONAL and this workbook
WkbCount = WkbCount - 2
Debug.Print "WkbCount: " & WkbCount
'Must be at least 1 other open workbook to continue
If WkbCount = 0 Then Exit Sub
For Each oWb In Application.Workbooks
'Ignore PERSONAL and this workbook
If oWb.Name <> "PERSONAL.XLSB" And oWb.Name <> ActiveWorkbook.Name Then
'If only 1 other workbook, do macro on that
If WkbCount = 1 Then
Workbooks(oWb.Name).Activate
DO_THIS_MACRO
Exit Sub
End If
Workbooks(oWb.Name).Activate
numa = MsgBox("There are " & WkbCount & " workbooks open. Do this on " & oWb.Name & "?", 3, "DO_THIS_MACRO")
If numa = 6 Then
' MsgBox "Yes option pressed!"
Workbooks(oWb.Name).Activate
DO_THIS_MACRO
' Exit or ask to do on all open
Exit Sub
ElseIf numa = 7 Then
'MsgBox "No option pressed!"
Else
' MsgBox "Cancel pressed!"
Exit Sub
End If
End If
Next oWb
End Sub

Excel VBA: How to activate a workbook without its complete name?

I have multiple excel workbooks open. I want to activate a workbook which has "Final" in its name.
Example: I have three open workbooks called "Workbook1.xlsx", "worKbook2.xlsm" and "workbookFinal.xlsx" open at the same time.
My VBA code is in "Macro.xlsm". Using VBA I want to activate the workbook which has "Final" in it. FYI .. all workbooks are in different paths.
Try the code below, using the Like Operator with the wild-card *.
Option Explicit
Sub FindFinalWorkbook()
Dim wb As Workbook
' loop through all open workbooks
For Each wb In Application.Workbooks
If wb.Name Like "*Final*" Then '< -- check if workbook name is Like *Final*
wb.Activate
Exit For
End If
Next wb
End Sub
loop through Workbooks collection until finding the right named workbook:
Sub wbs()
Dim wb As Workbook
For Each wb In Workbooks
If InStr(wb.Name, "Final") > 0 Then
wb.Activate
Exit For
End If
Next
End Sub

Working with multiple workbooks and Macros - Calling workbooks? [VBA]

I've got probably what is a simple question but I can't figure out what's going wrong. I'm trying to create one big Macro in excel that will do multiple things to multiple files. The context:
The excel sheet I am running the Macro from is in its own folder. I've set up a little testing folder with this structure:
C:\Users\schris\Desktop\Eprime Testing\
This folder has two folders in it:
\Master Dataset\
In this folder is where the excel file with the macro is
\Eprime Processing\
There are three folders in this folder, named 'Fear', 'Gender', and 'Happy'. In each of those folders is an excel file that I wish to open.
What I wanted to do was create a Sub RunAll that would call various other subs because there are many different things I want the Macro to do, and I wanted to keep it organized.
So:
Sub RunAll()
Call OpenWorkbooks
Call ProcessFear
Call ProcessGender
Call ProcessHappy
End Sub
Here is my OpenWorkbooks code:
Sub OpenWorkbooks()
Dim wb1 As Workbook
Dim wbFear As Workbook
Dim wbGender As Workbook
Dim wbHappy As Workbook
Dim FileToOpen As Variant
Dim FileToOpen2 As Variant
Dim FileToOpen3 As Variant
Dim Sheet As Worksheet
' Must be workbook with the Macros I'm running
Set wb1 = ActiveWorkbook
' Opens Fear
ChDir "C:\Users\schris\Desktop\Eprime Testing\Eprime Processing\Fear"
FileToOpen = Application.GetOpenFilename _
(Title:="Please choose Fear file")
If FileToOpen = False Then
MsgBox "No File Specified.", vbExclamation, "ERROR"
Exit Sub
Else
Set wbFear = Workbooks.Open(fileName:=FileToOpen)
End If
Set wbFear = ActiveWorkbook
' Opens Gender
ChDir "C:\Users\schris\Desktop\Eprime Testing\Eprime Processing\Gender"
FileToOpen2 = Application.GetOpenFilename _
(Title:="Please choose Gender file")
If FileToOpen2 = False Then
MsgBox "No File Specified.", vbExclamation, "ERROR"
Exit Sub
Else
Set wbGender = Workbooks.Open(fileName:=FileToOpen2)
End If
Set wbGender = ActiveWorkbook
' Opens Happy
ChDir "C:\Users\schris\Desktop\Eprime Testing\Eprime Processing\Happy"
FileToOpen3 = Application.GetOpenFilename _
(Title:="Please choose Happy file")
If FileToOpen3 = False Then
MsgBox "No File Specified.", vbExclamation, "ERROR"
Exit Sub
Else
Set wbHappy = Workbooks.Open(fileName:=FileToOpen3)
End If
Set wbHappy = ActiveWorkbook
End Sub
Now I want to be able to reference these three workbooks (wbFear, wbGender, wbHappy) and move seamlessly between them. When testing in Sub OpenWorkbooks(), doing wbFear.Activate would work and process correctly... But when I separated out the tasks of each macro (i.e., OpenWorkbooks now only opens the workbooks, ProcessFear only processes the data in the Fear workbook), I get a Run-time error '91': Object variable or With block variable not set.
I'm assuming this has something to do with the declared workbook names being 'lost' as it switches Subs, but when I put the code from OpenWorkbooks into RunAll and only had ProcessFear run, it still couldn't activate the proper workbooks.
Basically, my question is this:
How can I have one Macro open three workbooks, and declare them all as something that other macros can reference? There are many tasks I need to do, so I really want to have separate Subs for each one, that way I don't get lost in the code.
Thank you for your time!
There are better, more elegant solutions. But this is the simplest and also the easiest for you to implement. Declare 3 global object variables to hold the workbook references. Open the workbooks and assign to these variables in OpenWorkbooks. Use them as needed. Close them and set them to Nothing in a new procedure CloseWorkbooks. (Call is not needed in this context)
Public gwbFear as WorkBook
Public gwbGender as WorkBook
Public gwbHappy as WorkBook
Sub RunAll()
OpenWorkbooks
ProcessFear
ProcessGender
ProcessHappy
CloseWorkbooks
End Sub

How to select an open Excel file with different file ending name

I have an Excel Macro which look for specific file name Jobs in Lab.xlsx and copy to other macro file.
However, on certain event, the file naming may change to Jobs in Lab (0 - 195).xlsx.
How do I implement Excel Left Syntax into below VBA?
Sub Test()
Windows("Jobs in Lab").Activate
End Sub
You can use the LIKE operator.
Sub Sample()
Dim wb As Workbook
For Each wb In Application.Workbooks
If wb.Name Like "Jobs in Lab*" Then
wb.Activate
Exit Sub
End If
Next wb
End Sub
The code assumes that the file is opened in the same Excel instance.
EDIT:
However if you still want to use LEFT then you can use it like this. Notice the use of Ucase. It converts the text into upper case and then does a comparison. You can use LCASE as well.
Sub Sample()
Dim wb As Workbook
For Each wb In Application.Workbooks
If UCase(Left(wb.Name, 11)) = "JOBS IN LAB" Then
wb.Activate
Exit Sub
End If
Next wb
End Sub

Macro to copy and/or move selected sheets to a new workbook

Can someone please help me with a macro? I want to move and/or copy a few selected sheets (hidden & visible) to a new workbook, but since I have a few workbooks open at a time, I want to be able to select worksheets in all open workbooks from like a drop down menu and move and/or copy to a new workbook. I want to move some and copy some worksheets so will need both options in selection box.
Please help as I have cracked my head on it and got nowhere.
I have tried the below:
Sub CopySheet()
Dim i As Integer, x As Integer
Dim shtname As String
'i = Application.InputBox("Copy how many times?", "Copy sheet", Type:=1)
'For x = 0 To i - 1
ActiveSheet.Copy After:=Sheets(Sheets.Count)
shtname = InputBox("What's the new sheet name?", "Sheet name?")
ActiveSheet.Name = shtname
'Next x
End Sub
But this will mean I have to type every sheet name every time.
Adam: While I try to run your code, it gives me an error - variable not specified in row Private Sub btnSubmit_Click()
How do I overcome it?
I still can't get it right Adam. I am very new to Macros and I may be doing something wrong with interpreting your instructions. Can you please suggest something like all included in one and run?
Where exactly in the original codes do I need to paste this code
Private Sub btnSubmit_Click()
End Sub
This code should get you going. It is all of the code-behind for a UserForm with two listboxes, a checkbox, and a command button for submit. The dropdowns are populated automatically depending on what workbooks are open and what worksheets these workbooks contain. It also has the option to move or copy the selected worksheet. However, you still will need to add the functionality for copying the sheet multiple times, but that will just be a loop, and shouldn't be too difficult.
'All of this code goes in the section which appears when you right click
'the form and select "View Code"
Option Explicit
Public Sub OpenWorksheetSelect()
Dim WorksheetSelector As New frmWorksheetSelect
WorksheetSelector.Show
End Sub
Private Sub lstWorkbooks_Change()
FillWorksheetList
End Sub
Private Sub UserForm_Initialize()
FillWorkbookList
End Sub
Sub FillWorkbookList()
'Add each workbook to the drop down
Dim CurrentWorkbook As Workbook
For Each CurrentWorkbook In Workbooks
lstWorkbooks.AddItem CurrentWorkbook.Name
Next CurrentWorkbook
End Sub
Sub FillWorksheetList()
Dim WorkbookName As String
WorkbookName = lstWorkbooks.Text
If Len(WorkbookName) > 0 Then
Dim CurrentWorksheet As Worksheet
For Each CurrentWorksheet In Workbooks(WorkbookName).Sheets
lstWorksheets.AddItem CurrentWorksheet.Name
Next CurrentWorksheet
End If
End Sub
Private Sub btnSubmit_Click()
Dim WorkbookName As String, WorksheetName As String
WorkbookName = lstWorkbooks.Text
WorksheetName = lstWorksheets.Text
If Len(WorkbookName) > 0 And Len(WorksheetName) > 0 Then
If chkCopy = True Then
Workbooks(WorkbookName).Sheets(WorksheetName).Copy Before:=Workbooks.Add.Sheets(1)
Else
Workbooks(WorkbookName).Sheets(WorksheetName).Move Before:=Workbooks.Add.Sheets(1)
End If
End If
Unload Me
End Sub