Executing macro code from VBA script - vba

There is a way to convert VBA code to a script, so it can be executed without running it from an EXCEL macro?
For example this code below, I want to run it without the need of opening Excel file with the macro that contains it:
Sub XML_FILE()
Dim filename
MsgBox "Open File"
filename = Application.GetOpenFilename
If filename <> False Then
Workbooks.Open (filename)
MsgBox "Save File"
ActiveWorkbook.SaveAs filename:=filename, FileFormat:=xlOpenXMLWorkbook
End If
End Sub
What are the steps to make this and other macros to run as scripts?

Try this 1. Open notepad file and paste below code:
Dim objExcel, objWorkbook
Set objExcel = CreateObject("Excel.Application")
Set objWorkbook = objExcel.Workbooks.Open("C:\Folder\example.xlsm")
objExcel.Visible = False
objExcel.Run "XML_FILE"
objWorkbook.Close
objExcel.Quit
Set objWorkbook = Nothing
Set objExcel = Nothing
WScript.Echo "Finished."
WScript.Quit
Explanation
1.change objExcel.Run "Report" with your macro function name.
Then save the file as test.vbs then run the file it will run without opening the excel file.

Related

VBA open file in active worksheet

I am trying to create a code to open an Excel file (CSV file actually) in the active worksheet of a workbook. The file is not always located on the same location and does not always have the same name. Therefore I want the user to be able to browse the file.
I tried the code shown below. The code works partially, the code now opens the file in a new workbook. However, I would like to open the file/get the data in the active worksheet. Do you know how I could change the code to do this?
Sub OpenFile()
Dim FileName As String, test As Workbook
On Error GoTo ErrorMessage
FileName = Application.GetOpenFilename(, , "Browse for workbook")
'Open workbook
Workbooks.Open FileName
Set test = ActiveWorkbook
Exit Sub
ErrorMessage:
MsgBox ("Je hebt geen bestand geselecteerd, probeer het nogmaals.")
End Sub
You could just open the file copy the cells to the target worksheet.
Sub OpenFile()
Dim FileName As String
FileName = Application.GetOpenFilename("Comma Separated Values,*.csv", , "Browse for workbook")
If FileName = "False" Then Exit Sub
Dim TargetWorksheet As Worksheet
Set TargetWorksheet = ActiveSheet
Application.ScreenUpdating = False
With Workbooks.Open(FileName)
ActiveSheet.UsedRange.Copy TargetWorksheet.Range("A1")
.Close SaveChanges:=False
End With
End Sub
You could open the workbook the user selects and copy whatever sheet you need into your current workbook. Edit: This will paste it into your active sheet using UsedRange as others have shown.
Sub OpenFile()
Application.ScreenUpdating = False
Dim FileName As String, test As Workbook
Dim shActive As Worksheet
On Error GoTo ErrorMessage
FileName = Application.GetOpenFilename(, , "Browse for workbook")
'Open workbook
Set shActive = ActiveSheet
Set test = Workbooks.Open(FileName)
'copy the sheet you need from that workbook into your current workbook
test.Sheets(1).UsedRange.Copy shActive.Range("A1")
'close the previous workbook
test.Close SaveChanges:=False
Exit Sub
ErrorMessage:
MsgBox ("Je hebt geen bestand geselecteerd, probeer het nogmaals.")
End Sub

Open CSV file in background and retrieve worksheet name

My VBA project consists on cleaning databases.
I'm using a Userform, and this is the code i wrote till now.
I have been successful at importing a file, but i still can't perform actions on it.
I need you guys to show me how can i get the workbook name and worksheets of the .csv file i just imported to start assigning actions referring to the database by its workbook name and worksheet name.
I'd also appreciate it if you can show me how to keep my userform on top, or how to import the .csv file without displaying it
code
Dim fNameAndPath As Variant
Private Sub importedworkbook_Click()
MsgBox "imported workbook : " & _
fNameAndPath
End Sub
Private Sub Importbutton_Click()
fNameAndPath = Application.GetOpenFilename(FileFilter:="CSV Files Only (*.CSV), *.XLS", Title:="Select File To Be Opened")
If fNameAndPath = False Then Exit Sub
Workbooks.Open Filename:=fNameAndPath
End Sub
Best to use declared variables to reference the opened CSV sheet
Private wsCSV as Worksheet
Private Sub Importbutton_Click()
Dim wb as Workbook
fNameAndPath = Application.GetOpenFilename(FileFilter:="CSV Files Only (*.CSV), *.XLS", Title:="Select File To Be Opened")
If fNameAndPath = False Then Exit Sub
Set wb = Workbooks.Open(Filename:=fNameAndPath)
Set wsCSV = wb.Worksheets(1) ' A csv file will only ever have one sheet
End Sub
Variable wsCSV now refers to the CSV sheet, and can be referenced in other code in the UserForm module
You can open a second instance of Excel to work with the hidden file
Dim objExcel As Excel.Application
Dim wb As Workbook
fNameAndPath = Application.GetOpenFilename(FileFilter:="CSV Files Only (*.CSV), *.XLS", Title:="Select File To Be Opened")
If fNameAndPath = False Then Exit Sub
Set objExcel = New Excel.Application
Set wb = objExcel.Workbooks.Open(fNameAndPath)
Set wsCSV = wb.Worksheets(1)
MsgBox wsCSV.Name
' do stuff
'close second instance
wb.Close False
objExcel.Quit
Set objExcel = Nothing

how to save macro code as vbs?

I don't know why I can't call my macro code from R, This is my code that I'm trying to save as vbs file: (should I save it in Notepad application?)
Sub vb()
Dim xlApp
Dim xlBook
Set xlApp = CreateObject("Excel.Application")
Set xlBook = xlApp.Workbooks.Open("path.xlsm", 0, False)
xlApp.Visible = True
xlApp.Run "Countries"
xlApp.Quit
Set xlBook = Nothing
Set xlApp = Nothing
End Sub
How can I save the above code as vbs ?
You can export a code module from the project explorer, right-click on it and select Export File....
You can also do it with VBA, i.e. to export "Module1":
With ThisWorkbook.VBProject.VBComponents("Module1")
.Export "c:\so\" & .Name & ".bas"
End With
Use the below VBS code as you cannot save VBA code as VBS as the schema or say they are not in the same page as C and C++ are different it is in the same way
Set objExcel = CreateObject("Excel.Application")
Set objWorkbook = objExcel.Workbooks.Open("path.xlsm")
objExcel.Application.Visible = True
objExcel.Application.Run "path.xlsm!Countries" 'Refer to the below if the code is under sheet
objExcel.ActiveWorkbook.Close
WScript.Echo "Finished."
WScript.Quit
If you have placed the code in the sheet. user this line
objExcel.Application.Run "path.xlsm!sheet1.dog"
Hope this resolve your query. Happy Coding.

Workbook not activating in Excel by passing as an argument

I have a Book1.xls Excel workbook which has a macro written so that on workbook open the macro runs.
This macro takes all the CSV files in the workbook path and merges all the CSV into a single sheet say Master.xlsx which works fine and creates the Master.xlsx.
At the end of this macro I am calling another macro written in a module of same sheet and passing the Master.xlsx reference as workbook argument to another macro
Now what I want is that I need to set Master.xlsx passed an argument to this macro(module) as the current/active workbook so that I can format contents of the master.xlsx
My Code for the Book1.xls is :
Private Sub Workbook_Open()
'Create Excel application instance
Dim xlApp As Object
Dim dt, masterpath, folderPath, fileName, dtFolder As String
Set xlApp = CreateObject("Excel.Application")
'Setup workbooks
Dim wb As Excel.Workbook
Dim wBM As Excel.Workbook
Dim Wk As Workbook
fileName = "C:\Master.xlsx"
'Create a new Workbook
Set Wk = Workbooks.Add
Application.DisplayAlerts = False
Wk.SaveAs fileName:=fileName
Wk.Close SaveChanges:=False
Application.DisplayAlerts = True
'Csv files folder
Dim CSVfolder As String
CSVfolder = masterpath
'Master Excel file path
Dim mF As String
mF = fileName 'Where your master file is
'open the master file
Set wBM = xlApp.Workbooks.Open(mF)
'search and open the client files
Dim fname As String
fname = Dir(CSVfolder & "\*.csv")
Do While fname <> ""
'open the client file
Set wb = xlApp.Workbooks.Open(CSVfolder & "\" & fname)
'copy the first sheet from client file to master file
wb.Sheets(1).Copy After:=wBM.Sheets(wBM.Sheets.count)
'save master file
wBM.Save
'close client file
wb.Close False
'move to next client file
fname = Dir()
Loop
xlApp.Visible = True
Set xlApp = Nothing
Call AnotherMacroInModuleOfSameWorkbook(wBM)
End Sub
Code for Macro in Module of same Workbook
Sub AnotherMacroInModuleOfSameWorkbook(wb As Workbook)
wb.Activate
MsgBox (wb.Name)
MsgBox (ActiveWorkbook.Name)
End Sub
Here I'm getting "Master.xlsx" for alert 1 and "Book1.xls" for alert 2
What I wanted was that since I am passing reference of the Master.xlsx from the above macro and then activating the Master.xlsx in the below macro, the alert 2 should have given "Master.xlsx" as alert.
Please help.
Thanks.
By changing this line, the Master sheet opens now, where it wasn't before. It was just accessing it. I tested using my own workbooks, and used your code as a base. However, I didn't use all of your code, being that I don't have those objects. So it's mostly tested. I did generate the same errors you got before solving with this line, so I'm very certain this solves your problem:
Set wBM = Application.Workbooks.Open(mF)
The problem there is that when you open it, the code will break and need to be continued. To solve that, you need to place the following line before opening the workbook.
Application.EnableCancelKey = xlDisabled
BE WARNED: If you do this, you will not be able to break your code if you generate an infinite loop.
Please see this article about how to deal with EnableCancelKey
You are also trying to open a .xlsx file, instead of .xlsm Include this with your file creation statements.
FileFormat:= _xlOpenXMLWorkbookMacroEnabled
I found an workaround for this issue.
I tried closing the Master file generated (wBM) and again open the master workbook using Workbooks(mF).Open which ultimately gave me the current workbook (Master) as Active workbook.
Phewww..!!!! Hard time
Here's snapshot of the current working code:
Private Sub Workbook_Open()
'Create Excel application instance
Dim xlApp As Object
Dim dt, masterpath, folderPath, fileName, dtFolder As String
Set xlApp = CreateObject("Excel.Application")
'Setup workbooks
Dim wb As Excel.Workbook
Dim wBM As Excel.Workbook
Dim Wk As Workbook
fileName = "C:\Master.xlsx"
'Create a new Workbook
Set Wk = Workbooks.Add
Application.DisplayAlerts = False
Wk.SaveAs fileName:=fileName
Wk.Close SaveChanges:=False
Application.DisplayAlerts = True
'Csv files folder
Dim CSVfolder As String
CSVfolder = masterpath
'Master Excel file path
Dim mF As String
mF = fileName 'Where your master file is
'open the master file
Set wBM = xlApp.Workbooks.Open(mF)
'search and open the client files
Dim fname As String
fname = Dir(CSVfolder & "\*.csv")
Do While fname <> ""
'open the client file
Set wb = xlApp.Workbooks.Open(CSVfolder & "\" & fname)
'copy the first sheet from client file to master file
wb.Sheets(1).Copy After:=wBM.Sheets(wBM.Sheets.count)
'save master file
wBM.Save
'close client file
wb.Close False
'move to next client file
fname = Dir()
Loop
'close the current workbook
wBM.Close False
xlApp.Visible = True
Set xlApp = Nothing
'setting the reference again
Set newfile = Workbooks.Open(mF)
MsgBox (newfile.Name)
MsgBox (ActiveWorkbook.Name)
'Call to another module
Call AnotherMacroInModuleOfSameWorkbook(wBM)
End Sub
These two lines did the trick:
'close the current workbook
wBM.Close False
'setting the reference again
Set newfile = Workbooks.Open(mF)
Thanks for all the answers.

Creating and saving Excel document From VBA in Word

I want to be able to run a macro in a Word document that will create an Excel document and then save that spreadsheet in a shared folder.
This is the code I have so far:
Public Sub Monthly_Commission_Extract()
Dim objExcel
Dim objDoc
Dim objSelection
Dim SaveAs1 As String
SaveAs1 = ("\\stnlinasshd01\P403759\Month End\Monthly Commission Extract\1st Save")
Set objExcel = CreateObject("Excel.Application")
Set objDoc = objExcel.Workbooks.Add
objExcel.Visible = True
Set objSelection = objExcel.Selection
ActiveWorkbook.SaveAs FileName:=SaveAs1, FileFormat:=-4158, CreateBackup:=False
Application.DisplayAlerts = True
End Sub
The code is giving me an error:
Run-time error '424': Object required
At the following piece of code:
ActiveWorkbook.SaveAs FileName:=SaveAs1, FileFormat:=xlText, CreateBackup:=False
Please advise how I get around this.
objExcel.ActiveWorkbook.SaveAs
not just
ActiveWorkbook.SaveAs
Anything which "belongs" to Excel must be prefixed with your objExcel application reference.
Below is a simple and straight forward code that creates a new excel workbook and saves it into a path on your local disk. This VBA code has ben tested from inside MS Word.
Private Sub CreateExcel()
Dim myExcel As Object
Dim myWb As Object
Set myExcel = CreateObject("Excel.Application")
Set myWb = myExcel.Workbooks.Add
Application.DisplayAlerts = False
myWb.SaveAs FileName:="D:\test\dump.xls"
Application.DisplayAlerts = True
myWb.Close False
Set myWb = Nothing
myExcel.Quit
Set myExcel = Nothing
End Sub
In your case, the following would have worked because 'objDoc' is derived from the excel object reference.
objDoc.SaveAs FileName:=SaveAs1, FileFormat:=-4158, CreateBackup:=False
Oh captain, yes my captain,
the errormessage says clearly that a object is missed, I think this line
SaveAs1 = ("\stnlinasshd01\P403759\Month End\Monthly Commission Extract\1st Save")
is the problem You should a SET-Statement out of this, by starting this line with "SET ", then you have the object required.