excel vba 函数可以打开文件吗?

can excel vba function open a file?

我正在定义一个将文件保存为 .xls 格式的函数:

Public Function save_as_xls(full_file_path As String) As String
    save_as_xls = ""

    Dim src_file As Workbook
    Set src_file = Workbooks.Open(full_file_path)
    src_file.SaveAs filename:=full_file_path, FileFormat:=xlExcel8
    src_file.Close

    save_as_xls = "OK"
End Function

然后在 excel 单元格公式中将其调用为 =save_as_xls("c:\temp\test.xls")

但是,它不起作用,src_fileWorkbooks.Open

得到 Nothing

对于无法打开文件的vba函数是否有限制?我只知道它不能写入其他单元格。

Excel UDF有一定的局限性,不能保存工作簿。您可以尝试使用 Excel 的后期绑定实例的解决方法,如下面的代码所示。

将此代码放入标准模块:

Public objExcel As Application

Public Function SaveAsXls(FilePath As String) As String

    If objExcel Is Nothing Then
        Set objExcel = CreateObject("Excel.Application")
        With objExcel
            .Visible = True ' for debug
            .DisplayAlerts = False
        End With
    End If
    With objExcel
        With .Workbooks.Open(FilePath)
            .SaveAs _
                Filename:=FilePath, _
                FileFormat:=xlExcel8
            .Close True
        End With
    End With
    SaveAsXls = "OK"

End Function

将此代码放入 ThisWorkbook 部分:

Private Sub Workbook_BeforeClose(Cancel As Boolean)

    If TypeName(objExcel) = "Application" Then objExcel.Quit

End Sub

因此您可以在 Excel 单元格公式中将其调用为 =SaveAsXls("c:\temp\test.xls")