can excel vba function open a file? - vba

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.

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

Related

vba Macro to open other WB and execute Macro fails when other WB have userform show on opening

As topic implies I have a problem I cannot find any solution to.
I have a Workbook (1) with the purpose to open other WBs and run macros in them.
Everything works like a charm except when the other WB has Workbook_Open() event to open a Userform (typically it asks if the WB should be updated). Then I get error code 1004 and my code fails.
How could I supress the Workbook_Open event from triggering when I open another WB?
I have tried the setting Application.EnableEvents = False but it´s not related.
Thank you very much for any help on this topic!
Here is the code for opening the WB
Public Function wbTargetOpen(sTargetPath As String, SPassword As String) As Workbook
Dim sWBName As String
sWBName = Mid(sTargetPath, InStrRev(sTargetPath, "\") + 1, Len(sTargetPath) - InStrRev(sTargetPath, "\") + 1)
If WorkbookIsOpen(sWBName) Then
Set wbTargetOpen = Workbooks(sWBName)
If wbTargetOpen.ReadOnly = True Then
wbTargetOpen.Close
Set wbTargetOpen = Workbooks.Open(FileName:=sTargetPath, UpdateLinks:=0, ReadOnly:=False, WriteResPassword:=SPassword)
End If
Else
Set wbTargetOpen = Workbooks.Open(FileName:=sTargetPath, UpdateLinks:=0, ReadOnly:=False, WriteResPassword:=SPassword)
End If
If wbTargetOpen.ReadOnly Then sErrorCode = "ReadOnly"
End Function
All you have to do is add one word VbModeless to the other workbook which launches the userform.
Private Sub Workbook_Open()
UserForm1.Show vbModeless
End Sub
The vbModeless will launch the form but will also allow your macro to run.
Close the other userforms before you run the macros.
Sub CloseOtherUserForms()
Dim frm As UserForm
For Each frm In UserForms
If Not TypeName(frm) = "MacroForm" Then
Unload frm
End If
Next
End Sub

Copy range from workbook to another without open

I'm trying to copy a range of values from a workbook to another by using a dialog box to select the file I'd like to copy the data from.
I'd like also not to open the "copyFrom" workbook in the process. The problem lies in passing the file path in the string "filename" to the workbook variable "copyFrom".
Option Explicit
Private Sub butt_copy_Click()
Call copy1
End Sub
Private Sub copy1()
Dim fileName As String, copyFrom As Workbook
fileName = Application.GetOpenFilename()
copyFrom = filename
Sheet1.Range("A1:A20") = copyFrom.Sheets(Sheet1).Range("A1:A20")
End Sub
Just a comment to add to the algorithm;
It opens the file and reads from it, but does not close. This makes it "READ_ONLY" for all other users!
I suggest that at the end of the code: add this for saving original file unchanged.
Application.DisplayAlerts = False
app.Workbooks.Close savechanges:=False
Application.DisplayAlerts = True
Try Below. But i have some Clarification like where will you run the code from
Application.Visible=False
Set copyFrom = Application.Workbooks.Open(fileName)
Then Try below. Worked Perfectly for me
Private Sub copy1()
Dim app As New Excel.Application
Dim fileName As String, copyFrom As Workbook
app.Visible = False
fileName = app.GetOpenFilename()
Set copyFrom = app.Workbooks.Open(fileName)
MsgBox copyFrom.Sheets(1).Cells(1, 1)
'Sheet1.Range("A1:A20") = copyFrom.Sheets(Sheet1).Range("A1:A20")
End Sub

vba - Workbooks.Add(template) failing with out of range

I am trying to create a new workbook based on the formatting as that of an existing excel file and i am using the below code
sub newWorkBook()
Dim newWorkBook as New WorkBook
Set newWorkBook = WorkBooks.Add("Template.xls")
/*It is erroring on the above line*/
newWorkBook.Application.DisplayAlerts = False
With newWorkBook
.SaveAs "C:\new.xls"
End With
domainWorkBook.Save
domainWorkBook.Application.DisplayAlerts = True
domainWorkBook.Close
Set newWorkBook = Nothing
End Sub
It errors on the line Set newWorkBook = WorkBooks.Add("Template.xls") saying subscript out of range..
It also opens a new excel named Template1.xls and throws error...Any suggestions?
Why not just open the Template and SaveAs a new name?
Sub qwerty()
Workbooks.Open "C:\TestFolder\Template.xls"
ActiveWorkbook.SaveAs "C:\TestFolder\new.xls"
ActiveWorkbook.Close
End Sub

Calling VBA macro from .vbs file throws 800A03EC error

I'm trying to run a VBA macro through .VBS file(File name: Check_final.vbs). Here is the code
Option Explicit
run_macro
Sub run_macro()
Dim xl1
Dim sCurPath
Dim xlBook
Dim FolderFromPath
Set xl1 = CreateObject("Excel.application")
sCurPath =Wscript.ScriptFullName
Set xlBook = xl1.Workbooks.Open(sCurPath, 0, True)
xl1.DisplayAlerts = False
FolderFromPath = Left(sCurPath, InStrRev(sCurPath, "\"))
xl1.Application.run FolderFromPath & "Changed_chk.xlsm!Check"
Set xlBook = Nothing
End Sub
When I run this .vbs file I get this popup 'Changed_chk.xlsm is locked for editing' with Read only and notify options. If I acknowledge it with either Read only or notify option a excel sheet is opened in the name of Check_final (which is the file name of that .vbs file) and the above mentioned code is shown written in that excel file. Then I get a Windows script host error(code: 800A03AC) saying macro may not be available or all macro's are disabled.(Though I have enabled the macro as mentioned here.[http://www.addictivetips.com/windows-tips/enable-all-macros-in-excel-2010/)].
Any help on this is much appreciated. Thanks in advance.
You open your vbs-file instead of your excel-file... Also make sure that your function/sub is public. In the example below, I created a Public Sub Check in the module "YourModuleName", which I call from the vbs-file.
Option Explicit
run_macro
Sub run_macro()
Dim xl1
Dim xlBook
Dim FolderFromPath
Set xl1 = CreateObject("Excel.application")
FolderFromPath = Replace(WScript.ScriptFullName, WScript.ScriptName, "")
set xlBook = xl1.Workbooks.Open(FolderFromPath & "Changed_chk.xlsm")
xl1.Application.run "'" & xlBook.Name & "'!YourModuleName.Check"
xl1.Application.Quit
End Sub
Try this simple code (UNTESTED)
Dim oXlApp, oXLWb, sCurPath
Set oXlApp = CreateObject("Excel.application")
sCurPath = Replace(WScript.ScriptFullName, WScript.ScriptName, "")
Set oXLWb = oXlApp.Workbooks.Open(sCurPath & "Changed_chk.xlsm")
oXlApp.DisplayAlerts = False
oXlApp.Run "Check"
'~~> Close the file here. Save or discard the changes as per your requirement
'oXLWb.Close (True)
'oXLWb.Close (False)
oXLWb.Close
oXlApp.Quit
Set oXLWb = Nothing
Set oXlApp = Nothing
Also where is your macro? In a sheet or in a module? You may want to see THIS
I think there may be something wrong with calling the run_macro statement. From the test i created in excel VBA there is an error if i try to call the sub outside of another sub
Option Explicit
test
Sub test()
MsgBox ("Test")
End Sub
I think you may want to
Option Explicit
Sub Start
run_macro
End Sub
Sub run_macro()
'code here
End Sub
or remove the run_macro line altogether?

Save embedded word document from Excel VBA

I have created the below code for exporting an embedded Word document in a Excel Sheet to the workbook's path:
Private Sub Export()
Dim sh As Shape
Dim objWord As Object 'Word.Document
Dim objOLE As OLEObject
Set sh = Sheet1.Shapes("Object 1")
sh.OLEFormat.Activate
Set objOLE = sh.OLEFormat.Object
Set objWord = objOLE.Object
objWord.SaveAs2 Filename:=ActiveWorkbook.Path & "\MyTemplate.docx", FileFormat:= _
wdFormatDocumentDefault
End Sub
The above code is working fine, but I was looking to add that the Word Applications starts as invisible and that it exits MS Word at the end of the code. I have tried using objWord.Visible = False and objWord.Quit but when I add these lines I get an "Object doesn't support this property or method" error.
Please advise.
I guess you want this
objWord.Application.Visible = False
and this
objWord.Application.Quit