以下VBA代码在Windows中可以完美地从Excel复制表并将其粘贴到Word模板中。
在Mac上,粘贴步骤不起作用,并使Excel和Word崩溃(无错误消息,只是停止响应,我必须强制退出)。
我尝试使用
.Selection.PasteAndFormat Type:=wdFormatOriginalFormatting
代替
.Selection.PasteExcelTable False, False, False
但是我得到了相同的行为。
如果我在最后一步之前停止了宏,然后手动粘贴到Word中,它将起作用。该表已正确复制到剪贴板中,我可以将其粘贴。
Sub testPasteMac()
Dim wordApp As Object
Dim FName As String
Dim ws As Worksheet
Set ws = ThisWorkbook.Worksheets("Sheet1")
'Copy the table from Excel
ws.Range("A1:E4").Copy
'Open Word
On Error Resume Next
Set wordApp = GetObject(, "word.Application")
If Err = 429 Then
Set wordApp = CreateObject("word.Application")
Err.Clear
End If
'Display Word application
On Error Resume Next
wordApp.Activate
On Error GoTo 0
'Path to Word template file
FName = ThisWorkbook.Path & Application.PathSeparator & "FileName.dotx"
'Open template as new file
wordApp.Documents.Add Template:=FName
'Paste clipboard into Word document
With wordApp
.Selection.Goto what:=-1, Name:="bookmarkName"
.Selection.PasteExcelTable False, False, False
'.Selection.PasteAndFormat Type:=wdFormatOriginalFormatting
End With
End Sub
我使用Excel for Mac版本16.18 VisualBasic 7.1