我目前正在研究 excel 上的一个按钮,该按钮可以将 excel 中的数据邮件合并到 word 文档中。所以当它跑到线上时
Set wdocSource = wd.Documents.Open(c.Cells(529, 6).Value)
正如代码中的脚注,它有一个错误
“需要运行时错误‘424’对象”。
我已经创建并将所需的文档放在路径中,c.cells(529 .6)
但它不起作用。
其他 wdocSource 也可以,它可以将数据邮件合并到 c.cells 路径中指定的单词文档中,例如 c.cells(48, 6)。
这是一些代码。其他人只是在重复类似的东西,但条件不同,所以不会在这里展示,否则会很长。
Private Sub CommandButton1_Click()
Set c = ThisWorkbook.Worksheets("Path")
Dim i As Integer
i = 2
Do Until Cells(i, 3) = ""
If Cells(i, 2) = "N" Or Cells(i, 2) = "n" Or Cells(i, 2) = "E" Or Cells(i, 2) = "e" Or Cells(i, 2) = "+" Then
Dim wd As Object
Dim wdocSource As Object
Dim strWorkbookName As String
' Word constants
Const wdFormLetters = 0, wdOpenFormatAuto = 0
Const wdSendToNewDocument = 0, wdDefaultFirstRecord = 1, wdDefaultLastRecord = -16
On Error Resume Next
Set wd = GetObject(, "Word.Application")
If wd Is Nothing Then
Set wd = CreateObject("Word.Application")
End If
On Error GoTo 0
'path = ThisWorkbook.Worksheets("path").Cells(1, 1)
If Cells(i, 2) = "N" Or Cells(i, 2) = "n" Then
If Cells(i, 31) = 1 Then
If Cells(i, 5) = "A" Or Cells(i, 5) = "B" Or Cells(i, 5) = "C" Or Cells(i, 5) = "D" Or Cells(i, 5) = "E" Then
Set wdocSource = wd.Documents.Open(c.Cells(48, 6).Value)'this and others work just fine
ElseIf Left(Cells(i, 5), 24) = "F" Or Left(Cells(i, 5), 17) = "G" Then
Set wdocSource = wd.Documents.Open(c.Cells(529, 6).Value) '**The mentioned error occurs here**.
'repeating code...
End if
End if
End if
End if
strWorkbookName = ThisWorkbook.Path & "\" & ThisWorkbook.Name
wdocSource.MailMerge.MainDocumentType = wdFormLetters
wdocSource.MailMerge.OpenDataSource _
Name:=strWorkbookName, _
AddToRecentFiles:=False, _
Revert:=False, _
Format:=wdOpenFormatAuto, _
Connection:="Data Source=" & strWorkbookName & ";Mode=Read", _
SQLStatement:="SELECT * FROM [A$] where NO=" & i - 1
With wdocSource.MailMerge
.Destination = wdSendToNewDocument
.SuppressBlankLines = True
With .DataSource
.FirstRecord = wdDefaultFirstRecord
.LastRecord = wdDefaultLastRecord
End With
.Execute Pause:=False
End With
wd.Visible = True
wdocSource.Close SaveChanges:=False
Set wdocSource = Nothing
Set wd = Nothing
Else
End If
i = i + 1
Loop
End Sub
请帮忙!!