我正在尝试在 VBA 中编写一个程序,以便我可以从 SAS(一种统计编程软件)远程操作一个 excel 文件。我希望程序完成以下任务:
- 打开指定的excel文件
- 查找并替换标题行中的所有空白(例如,“测试名称”变为“测试名称”)
- 如果行中的第一个单元格(即 A2)为空白,则删除第二行
- 将文件另存为 csv
我不知道 VBA,稍微涉足过它,知道一些其他编程语言,并试图把它拼凑起来。我偷了一些代码来使 1 和 4 工作。我不能让 2 和 3 工作。这就是我所拥有的:
我将以下内容放入SAS中以调用vba程序-
x 'cd C:\Location';/*change to location of VBS file*/
x "vbsprogram.vbs inputfile.xls outputfile.csv";
VBA 程序 -
'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"
任何为我指明正确方向的帮助将不胜感激。
此外,有没有办法选择第 1 行中的所有数据作为范围(在第 2 部分中),而不必指定一组单元格范围?