ath*_*hos 3 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
Run Code Online (Sandbox Code Playgroud)
然后在excel单元格公式中将其称为 =save_as_xls("c:\temp\test.xls")
但是,这是行不通的,在src_file
获取Nothing
来自Workbooks.Open
无法打开文件的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
Run Code Online (Sandbox Code Playgroud)
将此代码放在以下ThisWorkbook
部分:
Private Sub Workbook_BeforeClose(Cancel As Boolean)
If TypeName(objExcel) = "Application" Then objExcel.Quit
End Sub
Run Code Online (Sandbox Code Playgroud)
因此,您可以在Excel单元格公式中将其称为 =SaveAsXls("c:\temp\test.xls")
归档时间: |
|
查看次数: |
1332 次 |
最近记录: |