我正在尝试用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 部分中),而不必指定一组单元格范围?
Try:
'2: - Find and Replace
oBook.Worksheets(1).Cells(2,1).EntireRow.Replace " ", ""
'3 - Delete second row if blank
If oExcel.CountA(oBook.Worksheets(1).Cells(2,1).EntireRow) = 0 Then
oBook.Worksheets(1).Cells(2,1).EntireRow.Delete
End If
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)