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

时间:2015-10-20 05:37:56

标签: excel vba excel-vba ms-word formatted-text

问题: 我想使用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

1 个答案:

答案 0 :(得分:1)

以这种方式修改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