can excel vba function open a file?

2.4k Views Asked by At

i'm defining a function to save files as .xls format:

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

However, it doesn't work, the src_file get Nothing from Workbooks.Open

Is there a limitation on vba functions that cannot open files? I only know that it can't write to other cells.

1

There are 1 best solutions below

4
omegastripes On BEST ANSWER

Excel UDF have certain limitations, so you can't save workbook. You may try a workaround with late bound instance of Excel as shown in the below code.

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:

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