英文:
Opening a workbook which its File_Name is not constant
问题
我正在寻找一个VBA解决方案,允许我打开一个具有可变文件名的文件。
这个文件名是一个固定名称和一个可变组件的组合。
名称的固定部分以“PM Wo 7.6”开头,然后是可变部分和文件的扩展名为.XLSB。
Dim wb As Workbook
Set wb = Workbooks.Open(ThisWorkbook.path & "\PM Wo 7.6" & VariableComponent & ".XLSB", UpdateLinks:=False, ReadOnly:=True)
英文:
I’m looking for a VBA solution that will allow me to open a file, which has a variable filename.<br>
This filename is a combination of a fixed name and a variable component. <br>
The fixed part of name begin with “PM Wo 7.6
” and then the variable part and the extension of file is .XLSB
.<br>
Dim wb As Workbook
Set wb = Workbooks.Open(ThisWorkbook.path & "\Name_of_File.xlsb", UpdateLinks:=False, ReadOnly:=True)
答案1
得分: 3
以下(未经测试)代码将打开找到的与文件模式匹配的文件夹中的第一个文件:
Sub open_with_pattern()
Dim fn As String
fn = Dir(ThisWorkbook.Path & "\PM Wo 7.6*.xlsb")
If fn = "" Then
MsgBox "未找到文件。"
Exit Sub
End If
Dim wb As Workbook
Set wb = Workbooks.Open(ThisWorkbook.Path & "\" & fn, UpdateLinks:=False, ReadOnly:=True)
'...
End Sub
注意:我注意到在您的问题中文件名有一个双空格,所以我复制了它,但如果所有文件名都是如此,您可能需要将其减少到一个空格。
英文:
The following (untested) code will open the first file in the folder it finds that matches the file pattern:
Sub open_with_pattern()
Dim fn As String
fn = Dir(ThisWorkbook.Path & "\PM Wo 7.6*.xlsb")
If fn = "" Then
MsgBox "No file found."
Exit Sub
End If
Dim wb As Workbook
Set wb = Workbooks.Open(ThisWorkbook.Path & "\" & fn, UpdateLinks:=False, ReadOnly:=True)
'...
End Sub
Note: I notice in your question the filename has a double-space so I've copied that but you might need to reduce it to one if that's all the filenames have.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论