4

我正在定义一个将文件保存为 .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_fileNothingWorkbooks.Open

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

4

1 回答 1

5

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")

于 2017-10-17T08:47:10.270 回答