简体   繁体   中英

Excel VBA open workbook with part of its name

I want to open, using VBA, a workbook from a certain path that includes a number, for example 2 . Any variation I tried is not working.

The name of the workbook is in Hebrew except for the number, so I want the VBA code to base the file name on the number to open the file.

I have 4 letters in hebrew before the number. In Hebrew we write from right to left.

Here is my code:

Set WB1 = Workbooks.Open("C:\RESULTS\" 2 & ".xlsx")

Thanks for helping.

This works for me:

Option Explicit

Sub TestMe()

    Dim objFSO          As Object
    Dim objFolder       As Object
    Dim objFile         As Object
    Dim wbs             As Workbook

    Dim strExtension    As String
    Dim lngNumber       As String
    Dim lngAdditional   As Long
    Dim lngLenFile      As Long

    strExtension = ".xlsx"
    lngNumber = 20
    lngAdditional = 4

    Set objFSO = CreateObject("Scripting.FileSystemObject")
    Set objFolder = objFSO.GetFolder("C:\Users\Desktop\")
    lngLenFile = Len(strExtension) + Len(lngNumber) + lngAdditional

    For Each objFile In objFolder.Files
        If Left(objFile.Name, Len(lngNumber)) = lngNumber And _
                Right(objFile, Len(strExtension)) = strExtension And _
                Len(objFile.Name) = lngLenFile Then

            Debug.Print objFile.Name
            Set wbs = Workbooks.Open(objFile)

        End If
    Next objFile

End Sub

The idea of the code is to make it flexible, thus, lngNumber and strExtension are added. It checks always for the size, as well as for right and left. Thus 24Some.xlsx would be different than 2Some.xlsx .

Debug.Print is added to see the file that is opened.

lngAdditional is added, for the additional 4 chars.

Try this

Dim sFound As String, fPath As String

fPath = "C:\RESULTS\"
sFound = Dir(fPath & "*2*.xlsx")   'get the first file in dir
If sFound <> "" Then
    Set WB1 = Workbooks.Open(fPath & sFound)
End If

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