VBA – 打开excel,find并replace,删除行,另存为csv
我想在VBA中编写一个程序,以便我可以远程操作SAS(一种统计编程软件)的Excel文件。 我希望程序完成以下任务:
- 打开指定的excel文件
- find并replace标题行中的所有空白(例如,“Test Name”变成“TestName”)
- 如果行(即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"
任何帮助指引我在正确的方向将不胜感激。
另外,是否有办法select行1中的所有数据作为范围(在第2部分),而不必指定一个设置范围的单元格?
尝试:
'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
根据您的input,您需要修改原始代码的语句(2)和(3),并将第1行中的所有单元格的值连接起来。您可以通过循环对应于行的2个Range对象中的每个单元格1和2.在Excel VBA中的操作的一般语法(来源: http : //msdn.microsoft.com/en-us/library/office/aa221353%28v=office.11%29.aspx )显示在下面示例代码片段:
Sub FormatRow1() For Each c In Worksheets("Sheet1").Range("A1:G1").Cells if (c.Value) = {condition} then do something. Next End Sub
FYI:使用&
运算符执行Excel VBA中的string连接。 另外,您应该使用Replace ( string1, find, replacement, [start, [count, [compare]]] )
和Range(range).EntireRow.Delete
VBA操作符完成任务。