目录
在 VBA 中,打开文件的方式有几种,每种方式适用于不同的情况:
1 Application.GetOpenFilename
- Application.GetOpenFilename 方法:
- 适用于需要让用户手动选择文件的情况。
- 优点是简单易用,不需要引用其他对象或库。
- 缺点是无法直接通过 VBA 程序打开文件,需要用户手动选择。
filePath = Application.GetOpenFilename("Excel Files (*.xls; *.xlsx), *.xls; *.xlsx")
2 Application.GetOpenFilename 方法 + Workbooks.Open 方法
- Application.GetOpenFilename 方法 + Workbooks.Open 方法:
- 适用于需要在 VBA 程序中打开用户手动选择的文件的情况。
- 可以在用户选择文件后,直接通过 VBA 代码打开所选文件。
- 优点是灵活,能够在程序中自动处理文件的打开。
- 缺点是需要用户手动选择文件,不够自动化。
filePath = Application.GetOpenFilename("Excel Files (*.xls; *.xlsx), *.xls; *.xlsx")
If filePath <> "False" Then
Workbooks.Open filePath
End If
2.1 用户选择打开文件
由于打开文件的时候如果已经被打开会弹窗是否需要重新打开,所以为了避免每次点弹窗选择,我们可以在代码中添加逻辑判断工作簿是否被打开,被打开了就直接获取,没被打开就重新打开。打开拿完对象后 使用完工作表可以直接Close。
'选择SIP文件
Function OpenSIP_WorkBook() As Workbook
Dim filePath As String
Dim fileName As String
Dim wb As Workbook
Dim wbIsOpen As Boolean
' 使用文件对话框选择文件
filePath = Application.GetOpenFilename("Excel Files (*.xls; *.xlsx), *.xls; *.xlsx")
' 检查是否选择了文件
If filePath <> "False" Then
' 获取文件名
fileName = Right(filePath, Len(filePath) - InStrRev(filePath, "\"))
' 检查工作簿是否已经打开
For Each wb In Workbooks
If wb.name = fileName Then
wbIsOpen = True
Exit For
End If
Next wb
'