I am trying to write a program in VBA so that I can remotely manipulate an excel file from SAS (a statistical programming software). I want the program to accomplish the following:
- open the specified excel file
- find and replace all blanks in the header row with nothing (e.g., "Test Name" become "TestName")
- delete the second row if first cell in row (i.e., A2) is blank
- save the file as a csv
I do not know VBA, have dabbled with it a little, know some other programming languages, and have tried to piece this together. I stole some code to make 1 and 4 work. I cannot get 2 and 3 to work. This is what I have:
I put the following in SAS to call the vba program -
x 'cd C:\Location';/*change to location of VBS file*/
x "vbsprogram.vbs inputfile.xls outputfile.csv";
The VBA Program -
'1 - Open the specified excel file
if WScript.Arguments.Count < 2 Then
WScript.Echo "Error! Please specify the source path and the destination. Usage: XlsToCsv SourcePath.xls Destination.csv"
Wscript.Quit
End If
Dim oExcel
Set oExcel = CreateObject("Excel.Application")
Dim oBook
Set oBook = oExcel.Workbooks.Open(Wscript.Arguments.Item(0))
'2 - Find and Replace
oBook.Worksheets(1).Range("A1:G1").Select
Selection.Replace What:="* *", Replacement:="", LookAt:=xlPart, _
SearchOrder:=xlByRows, MatchCase:=False
'3 - Delete second row if blank
oBook.Cell("A2").SpecialCells(xlCellTypeBlanks).EntireRow.Delete
'4 - Save as csv
oBook.SaveAs WScript.Arguments.Item(1), 6
oBook.Close False
oExcel.Quit
WScript.Echo "Done"
Any assistance pointing me in the right direction would be much appreciated.
Also, is there a way to select all data in row 1 as the range (in part 2) and not have to specify a set range of cells?