简体   繁体   中英

Excel VBA Code to select opened Excel file

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

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

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