将多个Excel工作表中的表格粘贴到Word文件中,并将单词命名为工作表名称VBA

时间:2018-10-14 15:19:06

标签: excel vba word-vba

我的Excel文件很多。在每张纸上,我有3个表格,需要将它们粘贴到Word文档中。我需要创建一个单词模板并将其命名为工作表并粘贴2个表。

Sub Separate()

 'Remember: this code requires a referece to the Word object model

 'dimension some local variables
Dim rng As Range 'our source range
Dim wdApp As New Word.Application 'a new instance of Word
Dim wdDoc As Word.Document 'our new Word document
Dim t As Word.Range 'the new table in Word as a range
Dim myWordFile As String 'path to Word template


 'initialize the Word template path
 'here, it's set to be in the same directory as our source workbook
myWordFile = ThisWorkbook.Path & "\DocWithTableStyle.dot"

 'get the range of the contiguous data from Cell A1
Set rng = Range("A1").CurrentRegion
 'you can do some pre-formatting with the range here
rng.HorizontalAlignment = xlCenter 'center align the data
rng.Copy 'copy the range

 'open a new word document from the template
Set wdDoc = wdApp.Documents.Add(myWordFile)

Set t = wdDoc.Content 'set the range in Word
t.Paste 'paste in the table
With t 'working with the table range
    .Style = "GreenBar" 'set the style created for the table
     'we can use the range object to do some more formatting
     'here, I'm matching the table with using the Excel range's properties
    .Tables(1).Columns.SetWidth (rng.Width / rng.Columns.Count), wdAdjustSameWidth
End With

 'until now the Word app has been a background process
wdApp.Visible = True
 'we could use the Word app object to finish off
 'you may also want to things like generate a filename and save the file
wdApp.Activate

End Sub

这是我正在尝试但出现错误的情况

---------------------------
Microsoft Visual Basic for Applications
---------------------------
Compile error:

User-defined type not defined
---------------------------
OK   Help   
---------------------------

选择对word和excel的引用

Download Example文件。 我不知道该如何编码,所以不要让我太难受

2 个答案:

答案 0 :(得分:1)

我已经更新了代码,检查并告诉我它是否有效?

在运行宏之前,请转到“ Microsoft Visual Basic for Applications”窗口

然后在工具->引用中

并检查“ Microsoft Word xx对象库”

好吧

然后删除您粘贴在模板中的表并将其保存,因为宏会粘贴该表,因此您不需要两个。

更新的宏

SerializedObject serializedObject;

public void SetObject(MyObject obj) {
  serializedObject = new SerializedObject(obj);
}

public override void OnDisplay() {
  accessType = serializedObject.FindProperty("accessType");
  key = serializedObject.FindProperty("key");
  value = serializedObject.FindProperty("value");
}

public override void OnGUI() {
  EditorGUILayout.PropertyField(valueType);
  EditorGUILayout.PropertyField(key);

  if (key.stringValue.Trim().Length > 0) {
    switch (valueType.enumNames[valueType.enumValueIndex]) {
      case "Integer":
        value.intValue = EditorGUILayout.IntField(value.displayName, value.intValue);
        break;
    }
  }
}

答案 1 :(得分:0)

类似的事情应该可以完成工作。

Option Base 1 'Force arrays to start at 1 instead of 0

Sub ExcelTablesToWord()

'PURPOSE: Copy/Paste An Excel Table Into a New Word Document
'NOTE: Must have Word Object Library Active in Order to Run _
  (VBE > Tools > References > Microsoft Word 12.0 Object Library)
'SOURCE: www.TheSpreadsheetGuru.com

Dim tbl As Excel.Range
Dim WordApp As Word.Application
Dim myDoc As Word.Document
Dim WordTable As Word.Table
Dim TableArray As Variant
Dim BookmarkArray As Variant

'List of Table Names (To Copy)
  TableArray = Array("Table1", "Table2", "Table3", "Table4", "Table5")

'List of Word Document Bookmarks (To Paste To)
  BookmarkArray = Array("Bookmark1", "Bookmark2", "Bookmark3", "Bookmark4", "Bookmark5")

'Optimize Code
  Application.ScreenUpdating = False
  Application.EnableEvents = False

'Set Variable Equal To Destination Word Document
  On Error GoTo WordDocNotFound
    Set WordApp = GetObject(class:="Word.Application")
    WordApp.Visible = True
    Set myDoc = WordApp.Documents("Excel Table Word Report.docx")
  On Error GoTo 0

'Loop Through and Copy/Paste Multiple Excel Tables
  For x = LBound(TableArray) To UBound(TableArray)

    'Copy Table Range from Excel
      Set tbl = ThisWorkbook.Worksheets(x).ListObjects(TableArray(x)).Range
      tbl.Copy

    'Paste Table into MS Word (using inserted Bookmarks -> ctrl+shift+F5)
      myDoc.Bookmarks(BookmarkArray(x)).Range.PasteExcelTable _
        LinkedToExcel:=False, _
        WordFormatting:=False, _
        RTF:=False

    'Autofit Table so it fits inside Word Document
      Set WordTable = myDoc.Tables(x)
      WordTable.AutoFitBehavior (wdAutoFitWindow)

  Next x

'Completion Message
  MsgBox "Copy/Pasting Complete!", vbInformation
  GoTo EndRoutine

'ERROR HANDLER
WordDocNotFound:
  MsgBox "Microsoft Word file 'Excel Table Word Report.docx' is not currently open, aborting.", 16

'Put Stuff Back The Way It Was Found
EndRoutine:
'Optimize Code
  Application.ScreenUpdating = True
  Application.EnableEvents = True

'Clear The Clipboard
  Application.CutCopyMode = False

End Sub