这是我使用VBA的第三天。我目前正在为这家公司签订一份为期3个月的合同,并且已经找到了如何自动将数据从excel转移到新的word文档(他们多年来一直想要的过程)。我还发现了如何从excel打开现有的word文档。
问题是,我还没有弄清楚如何将数据从excel传输到现有的word文档。
以下是我因上述原因而尝试编写的代码。谁能指出我哪里出错?任何和所有答案将不胜感激:)
Sub CopyRangeToWord()
Dim objWord As Word.Application
Dim objDoc As Word.Document
Set wordApp = GetObject("C:\Users\CoffeeFuelsMeNow\Documents\Ladedadeda\Testplate.dotx")
Set objDoc = objWord.Documents
objWord.Visible = True
Range("A1:B10").Copy
With objDoc.Paragraphs(objDoc.Paragraphs.Count).Range
'All formatting goes here
.Paste
.Font.Name = "broadway"
.Font.Color = wdColorBlue
.Font.Bold = True
.Font.Italic = True
.Font.Allcaps = True
.Font.Size = 20
End With
End Sub
答案 0 :(得分:1)
这对我来说非常合适:如果我执行代码,它会一次又一次地将行添加到文档中
Dim objWord
Dim objDoc
Set objWord = CreateObject("Word.Application")
Set objDoc =objWord.Documents.Open("C:\Users\schmidmath\Documents\test1.docx")
Range("A1:B10").Copy
With objDoc.Paragraphs(objDoc.Paragraphs.Count).Range
'All formatting goes here
.Paste
.Font.Name = "broadway"
.Font.Color = wdColorBlue
.Font.Bold = True
.Font.Italic = True
.Font.Allcaps = True
.Font.Size = 20
End With
objWord.Visible = True
答案 1 :(得分:0)
以下修改过的代码在我的最后工作,测试它并让我知道它是否满足您的要求。
Sub CopyRangeToWord()
Dim objWord
Dim objDoc
Set objWord = CreateObject("Word.Application")
Set objDoc = objWord.Documents.Add
Set wordApp = GetObject("C:\Users\CoffeeFuelsMeNow\Documents\Ladedadeda\Testplate.dotx")
Set objDoc = objWord.Documents
objWord.Visible = True
Range("A1:B10").Copy
With objDoc.Paragraphs(objDoc.Paragraphs.Count).Range
'All formatting goes here
.Paste
.Font.Name = "broadway"
.Font.Color = wdColorBlue
.Font.Bold = True
.Font.Italic = True
.Font.Allcaps = True
.Font.Size = 10
End With
End Sub