提问人:Sidvi 提问时间:11/28/2017 最后编辑:Tiago MussiSidvi 更新时间:10/4/2020 访问量:362
从 Excel 复制到 Word。Word 创建大量空白页
Copying from Excel to Word. Word creates a lot of blank pages
问:
我有一些代码应该在excel中复制一系列带有数据的单元格,然后将其粘贴到word文档中。该代码运行良好,但问题是,当它将数据粘贴到 word 中时,表格后面会出现几个空白页。代码在下面。有没有人知道如何修复它,以便只有带有数据的部分被复制,而我可以摆脱空白页?
Sub ExportToWord()
'Option Explicit
Dim WordApp As Word.Application
Dim myDoc As Word.Document
Dim WordTable As Word.Table
Dim SrcePath As String
Dim sht As Worksheet
Dim LastRow As Long
Dim LastColumn As Long
Dim StartCell As Range
'Copies the specified range in excel
Set sht = Worksheets("Calculations")
Set StartCell = Range("M3")
'Refresh UsedRange
Worksheets("Calculations").UsedRange
'Find Last Row
LastRow = sht.Cells.Find("*", SearchOrder:=xlByRows, SearchDirection:=xlPrevious).Row
'Select Range
sht.Range("M3:R" & LastRow).Copy
'Create an Instance of MS Word
On Error Resume Next
'Is MS Word already opened?
If WordApp Is Nothing Then Set WordApp = CreateObject(class:="Word.Application")
'Clear the error between errors
Err.Clear
'If MS Word is not already open then open MS Word
If WordApp Is Nothing Then Set WordApp = CreateObject(class:="Word.Application")
'Handle if the Word Application is not found
If Err.Number = 429 Then
MsgBox "Microsoft Word could not be found, aborting."
GoTo EndRoutine
End If
On Error GoTo 0
'Make MS Word Visible and Active
WordApp.Visible = True
WordApp.Activate
'Create a New Document
Set myDoc = WordApp.Documents.Add
'Paste Table into MS Word
myDoc.Paragraphs(1).Range.PasteExcelTable _
LinkedToExcel:=False, _
WordFormatting:=False, _
RTF:=False
'Autofit Table so it fits inside Word Document
Set WordTable = myDoc.Tables(1)
WordTable.AutoFitBehavior (wdAutoFitWindow)
'Insert Header logo
SrcePath = ""
myDoc.Sections.Item(1).Headers(wdHeaderFooterPrimary) _
.Range.InlineShapes.AddPicture (SrcePath)
'Prompts users to save document
WordApp.Documents.Save NoPrompt:=False
EndRoutine:
'Optimize Code
Application.ScreenUpdating = True
Application.EnableEvents = True
'Clear The Clipboard
Application.CutCopyMode = False
'Closes the Word application and the document
On Error GoTo Err1:
myDoc.Close
WordApp.Quit
Set WordApp = Nothing
Err1:
End Sub
答:
0赞
Shinhye
10/4/2020
#1
有一种手动方法可以做到这一点。
选择您的表格,单击鼠标右键,然后转到“设置单元格格式”。 然后选择“数字”-“数字”-“确定”,就像我附上的图片一样。
我希望它对您有所帮助。
评论
LastRow = sht.Cells.Find("*", SearchOrder:=xlByRows, SearchDirection:=xlPrevious).Row
问题出在这一行(在我看来)。据我了解,它计算了要复制的错误行数。如果您的工作表有多个表格,则通过搜索最后一个非空白单元格的行来计算最后一行的方法可能会导致不需要的值。请参阅这篇文章以找到您可以实施的方法。大多数时候,我使用“查找列中的最后一行”,它工作得很好。