从excel表

时间:2018-04-30 07:48:23

标签: excel vba ms-word

我正在尝试基于excel表创建word文档,如下所示:

enter image description here

最后,这会创建3个文档,每个文档只有与之对应的行。我的问题是它没有保持行的格式。有人可以帮我这个吗?这是代码:

Sub NewWordDocument()

Dim wrdApp As Word.Application
Dim wrdDoc As Word.Document
Dim i As Integer
Dim j As Integer
Dim LineCount As Integer
Dim DocumentCount As Integer

LineCount = Application.CountA(Range("A:A")) ' To see how many lines should be inputed
DocumentCount = Application.CountA(Range("B2:AZ2")) 'To see how many documents should be created

For j = 1 To DocumentCount
    Set wrdApp = CreateObject("Word.Application")
    wrdApp.Visible = True
    Set wrdDoc = wrdApp.Documents.Add ' or 'Set wrdDoc =wrdApp.Documents.Open("C:\Foldername\Filename.doc") 'sample word operations

    wrdApp.Selection.TypeText Text:="Heading One"

    With wrdDoc    
    For i = 1 To LineCount
        If Cells(i + 2, j + 1).Value = "Yes" Then
            .Range.InsertAfter Cells(i + 2, 1) 'Different way to paste the text. It doesn't keep the formatting
            .Range.InsertParagraphAfter
        End If
    Next i

    If Dir("D:\" & Cells(2, j + 1).Value & ".docx") <> "" Then
    Kill "D:\" & Cells(2, j + 1).Value & ".docx"
    End If

    .SaveAs ("D:\" & Cells(2, j + 1).Value & ".docx")
    .Close ' close the document
    End With
    wrdApp.Quit ' close the Word application
    Set wrdDoc = Nothing
    Set wrdApp = Nothing

Next j
End Sub

如果我做手工,复制单元格,并在Word粘贴它完美的作品 - 保持格式和删除表,但是当我使用“Selection.PasteExcelTable假,假,假”,而不是“InsertAfter”,我简单地覆盖相同的文字,而不是添加到页面的末尾。

另外,如何将“标题一”格式化为粗体和中心?

1 个答案:

答案 0 :(得分:0)

我明白了 - 它可能不是最好的方式,但它或多或少对我有用。

option type  object
option Object.keys(options)  [ 'leagueCaption', 'matchday' ]
options  { leagueCaption:
   { country: 'FR',
     code: '451',
     codeName: 'LEAGUE_2',
     leagueCaption: 'Ligue 2 2017/18' },
  matchday: 32 }
 options.codeName  undefined
JSON.stringify(options)  {"leagueCaption":{"country":"FR","code":"451","codeName":"LEAGUE_2","leagueCaption":"Ligue 2 2017/18"},"matchday":32}
JSON.stringify(options.codeName)  undefined