如何使用 vba 更快地将格式化文本从 excel 复制到 word

How to copy formatted text from excel to word using vba faster

问题: 我想使用 excelvba-脚本将格式化文本从 excel 复制到 word。 脚本尽职尽责地复制信息,但速度太慢。

你能告诉我如何加快速度吗?

到目前为止,我的方法已记录在此虚拟文档中。 该脚本假定单元格 C1:C100 包含格式化文本。

一般信息。 我正在写一个 excelvba makro,将格式化的文本块复制到 word 文档。 每个文本块都有两个版本。宏跟踪变化 word-style.(删除:textcolor red 和 strikethrough 等) 并将结果复制到第三列。 这部分就像一个魅力。然后将第三列复制到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

修改你的copyWholeRange方法为:

Sub copyWholeRange(wdoc As Word.Document)

    Worksheets(1).Range("C1:C10").Copy
    wdoc.Range(wdoc.Range.End - 1, wdoc.Range.End).PasteSpecial Placement:=wdInLine, DataType:=wdPasteHTML

    wdoc.Tables(1).ConvertToText Separator:=wdSeparateByParagraphs
End Sub