调整同一段落不同部分的字体 – Excel VBA

我通过VBA将数据从Excel中提供给Word文档。 我想格式如下。

1. 售票#452345: Lorem ipsum dolor sit amet,consectetur adipiscing elit,sed do eiusmod tempor incididunt ut labore et dolore magna aliqua。

服务票据部分大胆和斜体,只是描述斜体。 服务票号和说明来自Excel中的不同单元格。

这是我的代码:

'' Bookmark where I will be inserting the data. wdApp.Selection.GoTo what:=-1, Name:="Service_Ticket_Comments" Dim i As Integer Dim serviceTicket As String For i = 4 To shAuditTrail.Range("A4").End(xlDown).Row '' Pulling comments from the comments column. If Not IsEmpty(Cells(i, 11)) Then serviceTicket = "Service Ticket #" & Cells(i, 1) wdApp.Selection.TypeText "Service Ticket #" & Cells(i, 1) wdApp.Selection.Font.Bold = True wdApp.Selection.Font.Italic = True wdApp.Selection.TypeText " - " & Cells(i, 11) & Chr(10) & Chr(10) wdApp.Selection.Font.Italic = True End If Next 

这使Service Ticket部分和描述变成粗体和斜体,因为select应用于整个部分。 我怎么只保留第一部分大胆和斜体,而另一部分只是大胆?

不要使用Selection ,而是使用Range ,就像在Excel中一样。

不清楚目标Word文档中的select来自哪里,所以我没有select以此为起点。 但是,通常只有在用户select目标时才使用这种技术。

 Dim rng as Word.Range Set rng = wdApp.Selection.Range rng.Text = serviceTicket rng.Font.Bold = True rng.Font.Italic = True rng.Collapse wdCollapseEnd rng.Text = Cells(i,11) & vbCr rng.Font.Bold = False rng.Font.Italic = True 

注意 :您应该为此格式创build/使用字符样式 ,而不是直接应用格式。 这导致更有效的代码和更易于pipe理的文档。

您可以使用“范围字符”属性格式化单元格中的特定字符。 (请参阅https://msdn.microsoft.com/en-us/library/office/ff198232.aspx )例如,下面的例程将斜体显示并将所有文本粗体显示为(包括每个单元格的searchstring)范围。 在这种情况下,被查找的string也作为parameter passing。

 Sub TestMacro() Call BoldItalicsPartofCell(Selection, ":") End Sub Sub BoldItalicsPartofCell(rng As Range, searchstr) Dim singlecell As Range 'Loop counter Dim beforecolon As Integer 'Starting position of search string For Each singlecell In rng beforecolon = InStr(singlecell, searchstr) - 1 + Len(searchstr) If beforecolon > 0 Then With singlecell.Characters(Start:=1, Length:=beforecolon).Font .FontStyle = "Bold Italic" '.Underline = True 'If you want udnerlined as well! End With End If Next End Sub 

使用InsertAfter

 wdApp.Selection.TypeText "Service Ticket #" & Cells(i, 1) wdApp.Selection.Font.Bold = True wdApp.Selection.Font.Italic = True wdApp.Selection.InsertAfter " - " & Cells(i, 11) & Chr(10) & Chr(10) wdApp.Selection.Font.Bold = False wdApp.Selection.Font.Italic = True 

这不是优雅的,但我做到了。

 If Not IsEmpty(Cells(i, 11)) Then With wdApp.Selection .Paragraphs.Indent .Font.Bold = True .Font.Italic = True .TypeText Chr(10) & Chr(10) & numList & ". " .Font.Underline = True .TypeText "Service Ticket #" & Cells(i, 1) & ":" .Font.Bold = False .Font.Underline = False .TypeText " " & Cells(i, 11) .Paragraphs.Reset End With numList = numList + 1 End If