无法将值从Excel复制到Word vba

时间:2018-09-15 08:45:30

标签: vba

如何从Excel 复制已定义的范围并将其粘贴到Word ?下面的代码将文本复制为表格,但是我想将其复制为文本(),其字体格式不包含表格。 尝试以不同方式使用 .PastSpecial ,但结果为DEBUG。也许有人知道解决方法?

Sub Word()

   Dim objWord

   Dim objDoc

   Dim objSelection

   Set objWord = CreateObject("Word.Application")

   Set objDoc = objWord.Documents.Add

   objWord.Visible = True

   Set objSelection = objWord.Selection


    Range("B51:B60").Copy

    With objDoc.Paragraphs(objDoc.Paragraphs.Count).Range
           'All formatting goes here
        .Paste
        .Font.Name = "Times New Roman"
        .Font.Color = black
        .Font.Size = 11

    End With

    objDoc.SaveAs ("D:\MyFirstSave")

End Sub

2 个答案:

答案 0 :(得分:0)

也许是这样吗?

Option Explicit
Const wdFormatPlainText As Long = 22
Public Sub Copy2Word()
    Dim objWord As Object, objDoc As Object

    Set objWord = CreateObject("Word.Application")
    Set objDoc = objWord.Documents.Add

    objWord.Visible = True

    ThisWorkbook.Worksheets("Sheet1").Range("B51:B60").Copy

    With objDoc.Paragraphs(objDoc.Paragraphs.Count).Range
        .PasteAndFormat wdFormatPlainText
        .Font.NAME = "Times New Roman"
        .Font.Color = vbBlack
        .Font.Size = 11
    End With
    'Other code
End Sub

Word enumerated constants

答案 1 :(得分:0)

您可以获得最后创建的表,并使用ConvertToText()方法对其进行操作:

Option Explicit

Sub Word()
    With CreateObject("Word.Application") ' create and reference a word application object
        .Visible = True ' make referenced object visible
        With .Documents.Add ' create and reference a new document of referenced word obejct
            Range("B51:B60").Copy ' copy the wanted Excel range
            With .Paragraphs(.Paragraphs.Count).Range ' reference referenced document last paragrapgh range
                .Paste
                .Font.Name = "Times New Roman"
                .Font.Color = vbBlack
                .Font.Size = 11
            End With
            .tables(.tables.Count).ConvertToText(Separator:=0).ParagraphFormat.Alignment = 0  ' wdSeparateByParagraphs = 0 and  wdAlignParagraphLeft = 0

            .SaveAs ("D:\MyFirstSave")
            .Close
        End With
    End With
End Sub