[英]can excel vba function open a file?
i'm defining a function to save files as .xls format: 我正在定义一个将文件保存为.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
then call it in excel cell formula as =save_as_xls("c:\\temp\\test.xls")
然后在excel单元格公式中将其=save_as_xls("c:\\temp\\test.xls")
为=save_as_xls("c:\\temp\\test.xls")
However, it doesn't work, the src_file
get Nothing
from Workbooks.Open
但是,它不起作用, src_file
从Workbooks.Open
获取Nothing
Is there a limitation on vba functions that cannot open files? 对无法打开文件的vba函数有限制吗? I only know that it can't write to other cells. 我只知道它不能写入其他单元格。
Excel UDF have certain limitations, so you can't save workbook. Excel UDF有一定的局限性,因此无法保存工作簿。 You may try a workaround with late bound instance of Excel as shown in the below code. 您可以尝试使用后期绑定的Excel实例进行解决方法,如下面的代码所示。
Put this code to the standard module: 将此代码放入标准模块:
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
Put this code to ThisWorkbook
section: 将此代码放入ThisWorkbook
部分:
Private Sub Workbook_BeforeClose(Cancel As Boolean)
If TypeName(objExcel) = "Application" Then objExcel.Quit
End Sub
So you can call it in Excel cell formula as =SaveAsXls("c:\\temp\\test.xls")
因此,您可以在Excel单元格公式中将其=SaveAsXls("c:\\temp\\test.xls")
为=SaveAsXls("c:\\temp\\test.xls")
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.