简体   繁体   English

Excel VBA打开工作簿及其部分名称

[英]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 . 我想使用VBA从包含数字的特定路径(例如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. 除数字外,工作簿的名称以希伯来语命名,因此我希望VBA代码将文件名基于数字来打开文件。

I have 4 letters in hebrew before the number. 我在数字前有4个希伯来字母。 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. 该代码的思想是使其具有灵活性,因此添加了lngNumberstrExtension It checks always for the size, as well as for right and left. 它始终检查大小以及左右。 Thus 24Some.xlsx would be different than 2Some.xlsx . 因此, 24Some.xlsx将不同于2Some.xlsx

Debug.Print is added to see the file that is opened. 添加Debug.Print以查看已打开的文件。

lngAdditional is added, for the additional 4 chars. lngAdditional已添加,用于额外的4个字符。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM