使用VBScript编辑Excel文件,但编辑花费太长时间才能完成

/ *我之所以用vb脚本来编辑excel文件,是因为excel文件一直是不同的,但是格式是一样的,用户也不想在他们的工作簿上保存VBAmacros。

我从第3列中获取值,并将这些值添加到第9列的末尾。

* /

Set xlApp=CreateObject("Excel.Application") Set xlBook=xlApp.Workbooks.Open("filepath", 0, true) xlApp.visible=true Set xlSheet=xlBook.Worksheets("Proposal Spreadsheet") row=xlSheet.UsedRange.Rows.Count col=xlSheet.UsedRange.Columns.Count dim i For i=15 to xlSheet.UsedRange.Rows.Count cell=xlSheet.Cells(i,3).Value celli=xlSheet.Cells(i,9).Value+"("+cell+")" //I am combining column 3 with column 9 xlSheet.Cells(i,9).Value=celli Next xlBook.Save xlApp.Run "Submit_To_iDesk" xlBook.Close xlApp.Quit Set xlApp=Nothing Set xlBook=Nothing WScript.Quit 

如果UsedRange没有返回有用的数字,请使用find列中最后使用的单元格的更可靠的方法之一:

 Set xlApp=CreateObject("Excel.Application") Set xlBook=xlApp.Workbooks.Open("filepath", 0, true) xlApp.visible=true Set xlSheet=xlBook.Worksheets("Proposal Spreadsheet") row=xlSheet.Cells(xlSheet.Rows.Count, 9).End(-4162).Row ' -4162 is equivalent of "xlUp" dim i For i=15 to row cell=xlSheet.Cells(i,3).Value celli=xlSheet.Cells(i,9).Value xlSheet.Cells(i,9).Value=celli & "(" & cell & ")" Next xlBook.Save xlApp.Run "Submit_To_iDesk" xlBook.Close xlApp.Quit Set xlApp=Nothing Set xlBook=Nothing WScript.Quit 

加快程序的关键是减less写入操作的次数。
这是我该怎么做的

  • 将范围variables( 目标 )设置到第9列中的目标单元格
  • 从目标范围创build一个数组
  • 编辑values数组的元素将数组数组写回原始数组
  • 目标范围在1个操作中

 Set xlApp = CreateObject("Excel.Application") Set xlBook = xlApp.Workbooks.Open("C:\Users\best buy\Desktop\Book1.xlsx", 0, True) xlApp.Visible = True xlApp.ScreenUpdating = False Set xlSheet = xlBook.Worksheets("Proposal Spreadsheet") Dim i, values, LastRow, target With xlSheet LastRow = xlSheet.UsedRange.Rows.Count Set target = .Range(.Cells(15, 9), .Cells(LastRow, 9)) values = target.Value For i = LBound(values, 1) To UBound(values, 1) values(i, 1) = values(i, 1) & "(" & .Cells(i + 15 - LBound(values, 1), 3) & ")" Next target.Value = values End With xlBook.Save 'xlApp.Run "Submit_To_iDesk" xlBook.Close xlApp.ScreenUpdating = True xlApp.Quit Set xlApp = Nothing Set xlBook = Nothing WScript.Quit