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

时间:2017-10-17 04:19:05

标签: excel vba excel-vba excel-udf

我正在定义一个将文件保存为.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_file的{​​{1}}获取Nothing

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

1 个答案:

答案 0 :(得分: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")