VBS for selecting dynamic filename - excel

I know there are a lot of posts which say they are new to VBS, but honestly, I have never written VBS code before....
What I am trying to automate is a report and I have managed to cobble together the following:
Dim xlApp, xlBook
Set xlApp = CreateObject("Excel.Application")
xlApp.DisplayAlerts = False
Set xlBook = xlApp.Workbooks.Open ("C:\Users\pierre\Desktop\Test folder\16 10 19 Spreadsheet.xlsm", 0, True)
xlApp.Run "macro1"
xlbook.Save
xlBook.Close False
set xlBook = Nothing
xlApp.Quit
Set xlApp = Nothing
WScript.Echo "Finished."
WScript.Quit
Obviously it just opens an excel workbook at a specific location, runs a macro and ends, but what I dont understand is how to account for a dymanic filename in the code eg the date is going to change, but nothing else?
Is there a wildcard variable that can be used?
Any help please!

You can just store the date to a variable and use that in your filename:
Dim xlApp, xlBook
Dim formattedDate
formattedDate = Right(datepart("yy", Now), 2) & " " & DatePart("m", Now) & " " & DatePart("d", Now)
Set xlApp = CreateObject("Excel.Application")
xlApp.DisplayAlerts = False
Set xlBook = xlApp.Workbooks.Open ("C:\Users\pierre\Desktop\Test folder\" & formattedDate & " Spreadsheet.xlsm", 0, True)
xlApp.Run "macro1"
xlbook.Save
xlBook.Close False
set xlBook = Nothing
xlApp.Quit
Set xlApp = Nothing
WScript.Echo "Finished."
WScript.Quit
Here we use function datepart to get pieces of the current date Now. We also make use of function Right() which will get the right-most number of characters specified for the string in the first parameter. All of that is concatenated together using the & concatenation operator. Then with that formattedDate we just concatenate it right into the filename.

Related

Creating a macro-enabled Excel file from within Word VBA

The following code, when used within Word VBA, successfully creates a standard Excel workbook in the chosen folder:
Const ExcelSourcePath = "C:\Users\Holge\_Universet i billeder\_ExcelDocs\"
Dim xlAppl As New Excel.Application
Dim xlBook As New Excel.Workbook
Private Sub TestCreateExcelFile()
Set xlAppl = CreateObject("Excel.Application")
Set xlBook = xlAppl.Workbooks.Add
Application.DisplayAlerts = False
xlBook.SaveAs FileName:=ExcelSourcePath & "TestFile.xlsx"
Application.DisplayAlerts = True
xlBook.Close False
Set xlBook = Nothing
xlAppl.Quit
Set xlAppl = Nothing
End Sub
However, what I really need is to create a macro-enabled file. But if I change ".xlsx" into ".xlsm" I get a RTE 1004, "Wrong file type name" (translated from Danish).
Perhaps CreateObject should be called with another argument, but which one? I have not been alble to find possible values for this argument.
In the following code:
Dim xlAppl As New Excel.Application
Dim xlBook As New Excel.Workbook
Private Sub TestCreateExcelFile()
Set xlAppl = CreateObject("Excel.Application")
Set xlBook = xlAppl.Workbooks.Add
A new Excel Application instance is created twice. You need to keep the one line of code for create a new instance, not doing that twice.
Moreover, an instance of the Workbook class can't be created by using the New operator like shown in your code:
Dim xlBook As New Excel.Workbook
Most probably the intention was to declare objects out of the sub and then instantiate them:
Const ExcelSourcePath = "C:\Users\Holge\_Universet i billeder\_ExcelDocs\"
Dim xlAppl As Excel.Application
Dim xlBook As Excel.Workbook
Private Sub TestCreateExcelFile()
Set xlAppl = CreateObject("Excel.Application")
Set xlBook = xlAppl.Workbooks.Add
Application.DisplayAlerts = False
xlBook.SaveAs FileName:=ExcelSourcePath & "TestFile.xlsx"
Application.DisplayAlerts = True
xlBook.Close False
Set xlBook = Nothing
xlAppl.Quit
Set xlAppl = Nothing
End Sub
Just need to remove New operators from the code with declarations.

Run Excel Macro using VBS

Trying to run excel macro using command prompt through VBS. Excel file open ups but not able to run macro. The name of Macro as well as module is "Wallet"
While tryig to view macro, it reflects as "PERSONAL.XLSB!WALLET"
Pls help
Sub ExcelMacroExample()
Dim xlApp
Dim xlBook
Set xlApp = CreateObject("excel.application")
Set xlBook = xlApp.Workbooks.Open("C:\Output\abc.xlsb")
xlApp.Visible = True
xlApp.Run "Wallet"
xlApp.Save
xlApp.ActiveWorkbook.Close
xlApp.Quit
Set xlBook = Nothing
Set xlApp = Nothing
End Sub
Change your code like that
Sub ExcelMacroExample()
Dim xlApp
Dim xlBook
Set xlApp = CreateObject("excel.application")
Set xlBook = xlApp.Workbooks.Open("C:\Output\abc.xlsb")
xlApp.Visible = True
xlApp.Workbooks.Open ("Path to your Personal.XLSB")
xlApp.Run "Personal.XLSB!Macro"
'xlApp.Save <= This line would not work, xlApp does not have a Save Method
'xlApp.ActiveWorkbook.Close <= You already have the reference to the workbook. It is xlBook
xlBook.Close True ' <= This will save and close the workbook you opened
xlApp.Quit
Set xlBook = Nothing
Set xlApp = Nothing
End Sub
If you do not know where your Personal.xlsb is try the standard location.
xlApp.Workbooks.Open (xlApp.StartupPath & xlApp.PathSeparator & "Personal.XLSB")

Running Excel Macro from VBScript Subscript out of range

I am trying to print a file from a vbs script, and I am getting a subscript out of range. The macro works great when ran from excel.
The VBS script is:
dim xlApp
Set xlApp = CreateObject("Excel.Application")
xlApp.Application.Run "'C:\Users\jporter8\Documents\dashboard\testing.xlsm'!Module1.print_Test"
xlApp.DisplayAlerts = True
xlApp.Application.quit
set xlApp = Nothing
and the excel macro is:
Sub print_Test()
Sheets("two").PrintOut Copies:=1, Collate:=True, IgnorePrintAreas:=False
MsgBox "Print successful"
End Sub
And the sheet I am trying to print is named "two"
I found this work around to open the workbook so that the sheet existed and wasn't out of range
dim xlApp, xlBook
Set xlApp = CreateObject("Excel.Application")
set xlBook = xlApp.Workbooks.open("C:\Users\jporter8\Documents\dashboard\testing.xlsm", 0, true)
xlApp.Run "Module1.print_Test"
xlApp.DisplayAlerts = True
wscript.echo "Printed"
xlBook.Close
xlApp.Quit
set xlApp = Nothing
set xlBook = Nothing
wscript.echo "Finished"
wscript.Quit

VBA: Cannot implement Excel VBS outside of excel

I have the code shown below, which opens a workbook and runs the corresponding macro. Running this script through excel works just fine, but running the .vbs file with the same code does not run the macro. I have tried both double clicking the file and running it through the cmd prompt with "cscript.exe LaunchMacro.vbs". In addition, using WScript.Echo does not print to my command line. Am i missing something here?
Thank you!
Option Explicit
Sub LaunchMacro()
Dim xlApp, xlBook
Dim oShell: Set oShell = CreateObject("WScript.Shell")
oShell.CurrentDirectory = "H:"
Set xlApp = CreateObject("Excel.Application")
xlApp.Visible = True
xlApp.Application.Visible = False
Set xlBook = xlApp.Workbooks.Open("H:\SW Tool Resources\test\tester.xlsm")
MsgBox ("File Opened")
xlApp.DisplayAlerts = False
xlApp.Application.Run ("tester.xlsm!Module3.split")
MsgBox ("Application Should Have Run")
xlBook.Saved = True
xlApp.Quit
Set xlBook = Nothing
Set xlApp = Nothing
End Sub
VBS and VBA are different.
Try to put only this code in the vbs file and run it:
Set xlApp = CreateObject("Excel.Application")
xlApp.Visible = True
xlApp.Application.Visible = False
Set xlBook = xlApp.Workbooks.Open("H:\SW Tool Resources\test\tester.xlsm")
MsgBox ("File Opened")
xlApp.DisplayAlerts = False
xlApp.Application.Run ("tester.xlsm!Module3.split")
MsgBox ("Application Should Have Run")
xlBook.Saved = True
xlApp.Quit
I didn't test it, and very likely will not succeed. But it should put it in the right direction.
Edit:
Here is something that should help you getting started with VBS: a script can define some functions, but only runs them if you call them.
For example this will only run Sub1:
Sub Sub1()
MsgBox "1"
End Sub
Sub Sub2()
MsgBox "2"
End Sub
Sub1

Formatting outputted Excel files from Access using VBA?

Here I have some VBA code that outputs a ton of files into Excel files. My question is, from this, is there anyway for it to Format the excel file a bit? What I would like to do is make the Columns bold and make the columns fit the size of the header as well.
Sub OutPutXL()
Dim qdf As QueryDef
Dim rs As DAO.Recordset
Set qdf = CurrentDb.QueryDefs("OutputStudents")
Set rs = CurrentDb.OpenRecordset("Teachers")
Do While Not rs.EOF
qdf.SQL = "SELECT * FROM Students WHERE contact='" & rs!contact & "'"
''Output to Excel
DoCmd.TransferSpreadsheet acExport, acSpreadsheetTypeExcel8, _
qdf.Name, "C:\Users\chrisjones\Documents\ProjectionsFY14\Teachers\" _
& rs!contact & ".xls", True
rs.MoveNext
Loop
End Sub
this is a quick and dirty combination of Phil.Wheeler's Code and my previous input, for me this is working. Don't forget to add Excel's Object Library in your Access-Macro.
Sub doWhatIWantTheDirtyWay()
pathToFolder = "C:\Users\Dirk\Desktop\myOutputFolder\"
scaleFactor = 0.9
Set objExcel = CreateObject("Excel.Application")
objExcel.Visible = False
objExcel.DisplayAlerts = False
Set objFso = CreateObject("Scripting.FileSystemObject")
Set objFolder = objFso.GetFolder(pathToFolder)
For Each objFile In objFolder.Files
If objFso.GetExtensionName(objFile.path) = "xls" Then
Set objWorkbook = objExcel.Workbooks.Open(objFile.path)
For Each sh In objWorkbook.Worksheets
If sh.UsedRange.Address <> "$A$1" Or sh.Range("A1") <> "" Then
With sh
columncount = .Cells(1, 256).End(xlToLeft).Column
For j = 1 To columncount
With .Cells(1, j)
i = Len(.Value)
.ColumnWidth = i * scaleFactor
.Font.Bold = True
End With
Next
End With
End If
Next
objWorkbook.Close True
End If
Next
objExcel.Quit
End Sub
Yes it is possible! This is hacked together from one of my codes, might need a bit of editing before it works...
'This deals with Excel already being open or not
On Error Resume Next
Set xl = GetObject(, "Excel.Application")
On Error GoTo 0
If xl Is Nothing Then
Set xl = CreateObject("Excel.Application")
End If
Set XlBook = GetObject(filename)
'filename is the string with the link to the file ("C:/....blahblah.xls")
'Make sure excel is visible on the screen
xl.Visible = True
XlBook.Windows(1).Visible = True
'xl.ActiveWindow.Zoom = 75
'Define the sheet in the Workbook as XlSheet
Set xlsheet1 = XlBook.Worksheets(1)
'Then have some fun!
with xlsheet1
.range("A1") = "some data here"
.columns("A:A").HorizontalAlignment = xlRight
.rows("1:1").font.bold = True
end with
'And so on...
I have come across this problem a couple of times as well. As #Remou said, you will need to open excel to format xls files, this modification of your code silently opens Excel and that should get you in the right direction. Remember to add a reference to the Microsoft Excel Object Library in your VBA project.
Sub OutPutXL()
Dim qdf As QueryDef
Dim rs As DAO.Recordset
Dim xl as Excel.Application
Dim wb as Object
Dim strFile as string
Set qdf = CurrentDb.QueryDefs("OutputStudents")
Set rs = CurrentDb.OpenRecordset("Teachers")
Set xl = New Excel.Application
xl.DisplayAlerts = False
Do While Not rs.EOF
qdf.SQL = "SELECT * FROM Students WHERE contact='" & rs!contact & "'"
'Output to Excel
strFile = "C:\Users\chrisjones\Documents\ProjectionsFY14\Teachers\" & rs!contact & ".xls"
DoCmd.TransferSpreadsheet acExport, acSpreadsheetTypeExcel8, qdf.Name, strFile, True
'Start formatting'
Set wb = xl.Workbooks.Open(strFile)
With wb.Sheets(qdf.name)
'Starting with a blank excel file, turn on the record macro function'
'Format away to hearts delight and save macro'
'Past code here and resolve references'
End With
wb.save
wb.close
set wb = Nothing
rs.MoveNext
Loop
xl.quit
set xl = Nothing
End Sub
You could (depending on the number of files) make a template for each file you are outputting. In the long run if someone needs to change the formatting they can change the template which is going to be easier on you now that you don't have to sift through a bunch of excel formatting garbage. You could even let a qualified end user do it.
It's one of the biggest problems I have with excel sheets if I wrote the VBA I am responsible until I die for it. This way (in theory) they should be able to change a column, without changing how the data is outputted, just presented without you.
+1 To open the excel file itself and format it using that automation though.

Resources