问题: 我想使用 excelvba 脚本将格式化文本从 excel 复制到 word。脚本尽职尽责地复制信息,但速度太慢了。
你能给我一个提示如何加快速度吗?
到目前为止,我的方法记录在这个虚拟文档中。该脚本假定单元格 C1:C100 包含格式化文本。
一般信息。 我正在编写一个将格式化的文本块复制到 word 文档的 excelvba makro。每个文本块有两个版本。宏跟踪单词样式的变化。(删除:文本颜色红色和删除线等)并将结果复制到第三列。这部分就像一个魅力。然后将第三列复制到word文档中。这部分适用于我的机器(i7-3770,ssd,8 Gb Ram),但不适用于必须使用脚本(amd Athlon 220)的可怜的灵魂机器,生产大小为 700-1000 个文本块,100-1000 个字符每个。
option explicit
Sub start()
Dim wapp As Word.Application
Dim wdoc As Word.Document
Set wapp = CreateObject("word.application")
wapp.Visible = False
Application.ScreenUpdating = False
Set wdoc = wapp.Documents.Add
'Call copyFormattedCellsToWord(wdoc)
'Call copyFormattedCellsToWordForEach(wdoc)
'Call copyWholeRange(wdoc)
Call concatenateEverythingInAStringAndCopy(wdoc)
wapp.Visible = True
End Sub
'desired output-result (every cell in a new line and formatting preserved) meets the specs, but to slow
Sub copyFormattedCellsToWord(wdoc As Word.Document)
Dim counter As Long
Worksheets(1).Select
For counter = 1 To 100
Worksheets(1).Range("C" & counter).Copy
wdoc.Range(wdoc.Range.End - 1, wdoc.Range.End).PasteSpecial Placement:=wdInLine, DataType:=wdPasteHTML
Next counter
End Sub
'desired output-result, a tiny bit faster (might be only superstition), but still not fast enough
Sub copyFormattedCellsToWordForEach(wdoc As Word.Document)
Dim cell As Range
Worksheets(1).Select
For Each cell In Worksheets(1).Range("C1:C100")
cell.Copy
wdoc.Range(wdoc.Range.End - 1, wdoc.Range.End).PasteSpecial Placement:=wdInLine, DataType:=wdPasteHTML
Next cell
End Sub
'fast enough, but introduces a table in the word document and therefore
'doesn't meet the specs
Sub copyWholeRange(wdoc As Word.Document)
Worksheets(1).Range("C1:C100").Copy
wdoc.Range(wdoc.Range.End - 1, wdoc.Range.End).PasteSpecial Placement:=wdInLine, DataType:=wdPasteHTML
End Sub
'fast enought, looses the formatting
Sub concatenateEverythingInAStringAndCopy(wdoc As Word.Document)
Dim wastebin As String
Dim cell As Range
wastebin = ""
Worksheets(1).Select
For Each cell In Worksheets(1).Range("C1:C100")
wastebin = wastebin & cell.Value
Next cell
Range("D1") = wastebin
Range("D1").Copy
wdoc.Range(wdoc.Range.End - 1, wdoc.Range.End).PasteSpecial Placement:=wdInLine, DataType:=wdPasteHTML
End Sub