使用 vbscript 编辑 excel 文件,但编辑需要很长时间才能完成



/* 我使用 vb scrips 编辑 excel 文件的原因是:excel 文件会一直不同,但格式会相同,用户不想将 VBA 宏保存在他们的工作簿上。

我从第 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没有返回有用的数字,请使用更可靠的方法之一来查找列中最后一个使用的单元格:

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

加快过程的关键是减少写入操作的数量。
这是我会怎么做的

  • 将范围变量(目标(设置为第 9 列中的目标单元格
  • 从目标范围创建数组
  • 编辑值数组
  • 的元素 将值数组写回原始数组
  • 1次操作中的目标范围

Set xlApp = CreateObject("Excel.Application")
Set xlBook = xlApp.Workbooks.Open("C:Usersbest buyDesktopBook1.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

最新更新