How to automate formatting excel file via a VBA module - excel

I have a module that I wrote in VBA with excel. This module formats an excel sheet and saves a new file at a specified destination. So far I've just been importing the module into the VBA project and running the script from there.
I have tried using powershell for this but it is not my strong suit and I have been running into security issues with excel.
Severally summarized module:
'Essentially a lot of standard excel formatting, sorting, and fill colors
'Prompts for save location
Dim Fldr As String
With Application.FileDialog(4)
.AllowMultiSelect = False
If .Show <> -1 Then Exit Sub
Fldr = .SelectedItems(1)
End With
ActiveWorkbook.SaveAs Fldr & "\generated_report.xlsx", 51
Ideally I'd want an executable or script file that would prompt for the target excel file and then run the macro onto that file and save it in a destination, but all automatically.
The end-all be-all here would be a lightweight script file that could run without having to alter security settings within excel and could run on any machine with excel installed. Any help pointing me in the right direction for the method to use would be appreciated.

I ended up translating the VBA code into VBS, it opens the unformatted file and does operations onto it and then saves it as a new document. Works perfectly

Look into a VBA technique called Automation. One way you could solve the problem is with a .vbs script that Automates to each workbook file. You can run the .vbs script from the command line. E.g.:
https://www.experts-exchange.com/questions/23104413/Format-and-Excel-spreadsheet-using-vbscript.html

Related

Is it possible to run a macro externally on an excel file?

Currently, I export data daily from software to excel files.
There's a lot of repetitive tasks so I created a macro.
I open the new exported excel file and then save it as "Macro-Enabled worksheet"
I open the Macro-enabled worksheet
I import the macros into the excel file
I run the macros
Is there a way to run the macro without doing all the steps above using VBS or any other way?
I don't know if there's a solution out there, but I would prefer if an external VBA operator would ask for the location of the exported file and then does the rest
You can easily open any other workbook and run any commands on that workbook. So you can have the following macro in an Excel file MyMacroFile.xlsm and manipulate data in C:\Temp\WorkbookToRunMacroOn.xlsx for example.
Option Explicit
Public Sub DoTasksOnOtherWorkbook()
'open another workbook
Dim OpenWorkbook As Workbook
Set OpenWorkbook = Application.Workbooks.Open(Filename:="C:\Temp\WorkbookToRunMacroOn.xlsx")
OpenWorkbook.Worksheets("Sheet1").Range("A1").Value = "Changed A1 in another workbook"
'don't forget to close the workbook and save or not
OpenWorkbook.Close SaveChanges:=True
End Sub
If you want to ask the user to select a file to open you can use the Application.FileDialog property it returns a file name that you can then use in the Application.Workbooks.Open to open it.

Activating Macro view button sends excel in non-responding mode

In Excel 2013: macro was working fine until today. Now, I can open the "Personal.xlsb" file, but I cannot use the Macro view button anymore, all I get is Excel in unresponding mode; and then, only way is to stop Excel entirely. When I go in design mode, I cannot access the macro registry at all (trying to do so results in the same unresponding state). I rebooted the PC entirely, did not help.
Pb seems specific to one specific "Personal.xlsb" file (I replaced the incriminated file with another "Personal" file in the XSTART folder and Excel macros worked just fine with a different .xlsb file). So I am suspecting a file corruption pb. If that is the case, is it possible to recover the original macros, or at least crack the macro file open and get a copy of the original coding?
You can try to get back your code if you manage to open the workbook from a macro in another workbook. Give this a shot:
create a folder where you will get the recovered code modules. Let's say "C:\myRecoveredCode". Put in a copy of your corrupt file "Personal.xlsb"
In Excel Options, Trust Center Settings, Check Trust Access to the VBA project object module
create a fresh workbook, copy/paste and run the following macro:
Sub TryRecovery()
myFolder = "C:\myRecoveredCode\"
Set wb = CreateObject(myFolder & "Personal.xlsb")
For Each comp In wb.VBProject.VBComponents
comp.Export myFolder & comp.Name
Next
wb.Close False
End Sub
If all goes well, you will have files a set of files that you can edit, or import to another workbook.

Using VBS to open text file in excel and run macro without opening excel

This might sound confusing, and I'm not entirely sure it's possible to do it the way I want, but what I'm looking to do is create a script that will take a .txt file and run Excel macros on it, without actually opening up Excel or the file. One of the blogs I was reading suggested this method, but I'm not very familiar with VBS.
Set objExcel = CreateObject("Excel.Application")
objExcel.Application.Run "'Path\Test.xlsm'!Module.Macro"
objExcel.DisplayAlerts = False
objExcel.Application.Quit
Set objExcel = Nothing
This did not work when I tried to use it with a .txt file.
The error I receive is Cannot run the macro Path.... The macro may not be available in this workbook or all macros may be disabled
I'm sure it has something to do with my lack of VBS knowledge, but so far it's been the closest kind of script I've found for what I'm looking for. Is what I'm trying to do possible?
You need to open the workbook before you can run macros from it.
...
Set wb = objExcel.Workbooks.Open("C:\path\to\Test.xlsm")
objExcel.Application.Run "'Path\Test.xlsm'!Module.Macro"
...
You can't run a macro without opening Excel or the file containing the macro. If you want something like that you need to translate the VBA code to plain VBScript.
Path statement need full path eg " c:\ .... "
And I think it should be Module1.Macro_Name (not Module)
Write in note pad but save with .vbs on desktop. Just click on the run

How to open a csv file from Excel with a particular line highlighted?

I have a large CSV file and I want to programmatically open it in excel with a particular line highlighted (I know the line number). What is the easiest way to this?
I think my options are:
Auto convert the csv file to an xlsx file. How can I do this from a script?
Give Excel some arguments when it opens up. No idea what command line arguments Microsoft products take.
Somehow interact with Excel after it opens up the CSV file and tell it to highlight a particular. Again not sure how.
I prefer Java/Python/Shell or anything that would work across Mac/Windows assuming the system has Excel installed. So, my best bet is probably #1 which brings me back to the question how can I convert a CSV file to a xlsx file.
You could run a basic vbs which avoids the need to have Excel already open, and conversion isn't necessary.
Paste the code below into a text editor NotePad
Change the path to your CSV file to suit (ie "c:\temp\test2.csv")
Save the file as something like MyCSV.vbs say to your Desktop
Click on the final vbs to open the CSV file to Row X (8 in the sample below)
Dim objExcel
Dim WB
Set objExcel = CreateObject("excel.application")
Set WB = objExcel.Workbooks.Open("c:\temp\test2.csv")
With objExcel
.Goto WB.Sheets(1).Rows(8)
.Visible = True
End With
this works simple save it in an empty workbook.
Private Sub Workbook_Open()
Workbooks.Open ("test.csv")
Range("8:8").Select
End Sub
also if you save that in your normal.dot (the default template document when opening excel) it will run on any document it opens. so what you could do is:
save this to your normal.dot
Private Sub Workbook_Open()
Range("8:8").Select
End Sub
then change the default application for opening .csv files to excel. then whenever you double-click on .csv file it will be opened with excel and excel will run the Workbook_Open() sub and viola!

Why is this file always saved as FALSE.xls?

I wrote a VB script that creates an .xls file, based on .xlt file. Then it calls a macro from the .xls file that populates it with information from a database. In the last step the script saves the .xls file on the disk.
I did this before with VB and Excel 2003. Now I upgraded to Excel 2007 and before it saves the file, a window pops up and tells me that:
"The following features can't be saved in macro free workbooks:
VB project
...some yada yada about what the Yes and No option do.
And the yes and no buttons in the dialog box.
"
I want the script to automatically select and execute Yes in the dialog box. But I can't figure how to do this. I've also posted the script I wrote.
If you have a better approach for this please share.
Thank you,
Steve
Sub Main()
Dim xl_app
Set xl_app = CreateObject("Excel.Application")
xl_app.Workbooks.Open("E:\Work\Send Mail\Clienti.xls")
'Run the macro
xl_app.Run( "ImportData(""Data Source=SFA;Initial Catalog=Campofrio;
Integrated Security=SSPI;Connect Timeout=3000"", -1, 47)")
xl_app.ActiveWorkbook.SaveAs FileName="E:\Work\Send
Mail\Clients.xls",FileFormat=xlNormal
xl_app.Quit
Set xl_app = Nothing
End Sub
Now the cod works but instead of saving the file at the specified location, it saves it in My Documents folder under FALSE.xls.
Merging responses from the two duplicate questions the poster asked:
1
Preventing False.xls when saving files in Excel
2
You are using named parameters in the .SaveAs wrong. When writing out the named parameter you'll have to do it in the format
FileName:="e:\myfile.xls"
Notice the colon before the equal sign.
If you just write Filename="myfile.xls" then its a boolean comparison that will return false. And thats why it save the file as false.xls.
Really funny error I think. ;)
I'm not sure if this is the problem, but shouldn't you just be saving as a .xlsm instead of .xls, which lets you save a macro-enabled workbook in Office 2007? You can check which version the macro is running on and if it's Excel 2007 then save as .xlsm, .xls otherwise...
Do you really need to save it with the macros included? If not, use:
ActiveWorkbook.SaveAs Filename:="E:\Work\Send Mail\Clients.xls", FileFormat:=xlNormal
EDIT: the key is that the extension used should match the FileFormat specified. The above works for me (to exclude macros) and the below works for me (to include macros). Neither has any popup, and both end up in the right directory (as the other poster mentioned, you have to have the := if you specify FileName; otherwise, use the form below.
ActiveWorkbook.SaveAs "c:\temp\wordmacros\mybook.xlsm", xlOpenXMLWorkbookMacroEnabled

Resources