-1

I have the below working code. I added the With statement but it formats all text on page. This code takes each row from an excel table and extracts the column header (question) and the cell value (answer) just below it.

My goal is to have the question in bold and one font size and the answer below it normal font and a smaller size. I tried wrapping the With statement around just the header code but it still stylizes the entire page

For Each cell In tbl.DataBodyRange.Rows:

If cell.EntireRow.Hidden = False Then
    hiddenCell = cell.Row
    
    
    For Each Header In tbl.HeaderRowRange:

    With WordDoc
    .Styles(wdStyleHeading1).Font.Name = "Arial"
    .Styles(wdStyleHeading1).Font.Size = 12
    .Styles(wdStyleHeading1).Font.Bold = True
    .Styles(wdStyleHeading1).Font.Color = wdColorBlack
    .Range(0).Style = .Styles(wdStyleHeading1)
    
        headerCol = wks.Cells.Find(Header).Column
        WordDoc.Content.InsertAfter (vbNewLine)
        WordDoc.Content.InsertAfter Range(Header.Address).Value & ": "
        WordDoc.Content.InsertAfter (vbNewLine)
        WordDoc.Content.InsertAfter (Cells(hiddenCell, headerCol).Value)
        'WordDoc.Content.InsertAfter (vbNewLine)
    End With
        
    Next
WordDoc.Sections.Add
4

1 回答 1

0

首先,您需要从循环中定义标题 1。您只需要定义一次样式。

您还可以在循环中使用 Heading 1 样式格式化文档。同样,这不需要重复。

您的代码不做的是将任何其他样式应用于答案。

我重新起草了您的代码,为最后一段设置了文本和样式。

  With WordDoc
    With .Styles(wdStyleHeading1).Font
      .name = "Arial"
      .Size = 12
      .Bold = True
      .Color = wdColorBlack
    End With
    .Range(0).style = .Styles(wdStyleHeading1)
  End With

  For Each Cell In tbl.DataBodyRange.Rows:

    If Cell.EntireRow.Hidden = False Then hiddenCell = Cell.Row
    
    For Each Header In tbl.HeaderRowRange:

      With WordDoc
        headerCol = wks.Cells.Find(Header).Column
        
        .Content.InsertAfter (vbNewLine)
        With .Paragraphs.Last.Range
          .Text = Range(Header.Address).Value & ": "
          .style = wdStyleHeading1
        End With
        .Content.InsertAfter (vbNewLine)
        With .Paragraphs.Last.Range
          .Text = Cells(hiddenCell, headerCol).Value
          .style = wdStyleNormal
        End With
      End With
        
    Next Header
    WordDoc.Sections.add
  Next Cell
于 2020-07-26T14:07:01.020 回答