VBA打开文件的方式及各个方式的使用优劣 Application.GetOpenFilename、FileSystemObject(Scripting.FileSystemObject):

在 VBA 中,打开文件的方式有几种,每种方式适用于不同的情况:

1 Application.GetOpenFilename

  1. Application.GetOpenFilename 方法
    • 适用于需要让用户手动选择文件的情况。
    • 优点是简单易用,不需要引用其他对象或库。
    • 缺点是无法直接通过 VBA 程序打开文件,需要用户手动选择。
filePath = Application.GetOpenFilename("Excel Files (*.xls; *.xlsx), *.xls; *.xlsx")

2 Application.GetOpenFilename 方法 + Workbooks.Open 方法

  1. 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
        
        '
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值