VBA复制并将Excel表粘贴到Word文档中

时间:2015-06-15 17:51:27

标签: excel vba excel-vba

我正在编写的代码是使用工作表的已使用范围(不包括前两行)并将该表(或多个表)复制到word文档中的自己的页面上。代码工作正常,直到我不得不对它进行一些更改...现在问题是它循环遍历工作簿中的所有工作表,但只重新粘贴最后一个工作表的内容。另外,我似乎无法让VBA将粘贴的表识别为表格 - 所以它不会让我将它们放在word文档中。关于如何解决这些问题的任何想法?提前谢谢。

Sub toWord()
Dim ws As Worksheet
Dim fromWB As Variant
Dim wdApp As Object
Dim wdDoc As Object
Dim docName As Variant
Dim rng As Range

Application.ScreenUpdating = False
Application.DisplayAlerts = False
Application.EnableEvents = False


Set wdApp = CreateObject("Word.Application")
wdApp.Visible = True
Set wdDoc = wdApp.Documents.Add
wdDoc.Activate
'Creates InputBox that allows user to enter name to save document as
docName = Application.InputBox(Prompt:="Enter Document Name", Title:="Save Word Document", Type:=2)
wdDoc.SaveAs2 fileName:=docName, FileFormat:=wdFormatDocument 'Saves document under user-provided name

fromWB = Application.GetOpenFilename(FileFilter:="Excel Workbook(*.xlsx),*.xlsx", Title:="Open Merged Data")
If fromWB <> False Then
Set fromWB = Workbooks.Open(fromWB)
Set fromWB = ActiveWorkbook
ElseIf fromWB = False Then
    MsgBox "No File Selected"
    GoTo ResetSettings
End If


For Each ws In fromWB.Worksheets
    Range("A2").CurrentRegion.Offset(2).Resize(Range("A2").CurrentRegion.Rows.Count - 2).Select
    Selection.Copy
    Set wdApp = GetObject(, "Word.Application")
    wdApp.Visible = True
    wdDoc.Activate
    wdDoc.Range(wdDoc.Characters.Count - 1).Paste
    wdDoc.Range(wdDoc.Characters.Count - 1).InsertBreak Type:=7
    ActiveDocument.Tables(1).Select
    Selection.Tables(1).Rows.Alignment = wdAlignRowCenter
Next ws
   wdDoc.Styles("Normal").NoSpaceBetweenParagraphsOfSameStyle = True
wdDoc.Save
Set wdDoc = Nothing
Set wdApp = Nothing
MsgBox "Imported into Word Document"


ResetSettings:
Application.ScreenUpdating = True
Application.DisplayAlerts = True
Application.EnableEvents = True

End Sub

1 个答案:

答案 0 :(得分:2)

我在您的代码中看到的问题是: -

  1. Set fromWB = ActiveWorkbook是多余的,可以删除
  2. 您在没有工作表前缀的情况下引用Range,因此它始终默认为当前活动工作表(打开工作簿时可见的工作表)。通常我会说这样做:ws.Range("A2")但在这种情况下,我会建议ws.Activate作为For Each循环中的第一个语句,因为您正在使用复制/粘贴等物理操作。
  3. 要成为一名优秀的资源公民,您应该退出Excel并设置fromWB = Nothing以释放内存。实际上,在VBA中,您应该在离开方法之前将所有已分配的对象变量设置为Nothing