从Excel使用VBA,我想复制一个范围从Excel到Word,我被卡住了!我试图通过以下方式重新创建我手动完成的工作:
我尝试过在互联网上找到的多个版本的代码,但我无法让代码运行。我确实在Excel中将"Microsoft 16.0对象库“作为引用进行了检查。
我得到的错误是“运行时错误91 -对象变量或块变量未设置”。我已经在下面的代码中标记了它失败的地方。当我运行这个程序时,它会启动Word,但是它不会打开一个新文档。
这是我得到最远的密码。
Sub ExcelToWord()
Dim PageNumber As Integer
Dim wrdApp As Word.Application
Dim wrdDoc As Word.Document
Dim FileToOpen As String
Dim strPath As String
FileToOpen = "Excel Link test.docx"
strPath = "C:\"
'the next line looks to a cell to decide what page number to scroll to
PageNumber = 1 'Later
On Error Resume Next
Set wrdApp = GetObject(, "Word.Application")
If wrdApp Is Nothing Then
Set wrdApp = CreateObject("Word.Application")
Set wrdDoc = wrdApp.Documents.Open(strPath & FileToOpen)
On Error GoTo notOpen
Set wrdDoc = wrdApp.Documents(FileToOpen)
GoTo OpenAlready
notOpen:
Set wrdDoc = wrdApp.Documents.Open(strPath & FileToOpen)
End If
OpenAlready:
On Error GoTo 0
Range("A6:D11").Copy ' med WS Name
With wrdApp
'------> Fails Here
.Selection.Goto What:=1, Which:=2, Name:=PageNumber
.Visible = True
.Selection.Paste
End With
Set wrdDoc = Nothing
Set wrdApp = Nothing
End Sub
一如既往,谢谢你的帮助!
发布于 2021-12-17 08:08:34
请测试下一段代码。它将打开一个新的空白文档并使用它,而不是由代码打开的文档:
Sub ExcelToWord()
Dim PageNumber As Integer, wrdApp As Word.Application, wrdDoc As Word.Document
Dim sh As Worksheet
Set sh = ActiveSheet 'use here the sheet you need
PageNumber = 1
On Error Resume Next
Set wrdApp = GetObject(, "Word.Application")
If wrdApp Is Nothing Then
err.Clear: On Error GoTo 0
Set wrdApp = CreateObject("Word.Application")
End If
On Error GoTo 0
Set wrdDoc = wrdApp.Documents.Add 'add a blank document
wrdApp.Visible = True 'make Word application visible
'only for debugging, if not want to be visible
'and you will save it (programmatically) in the next steps...
sh.Range("A6:D11").copy ' med WS Name
With wrdApp