我通过VBA从Excel向Word文档提供数据。我想格式化 以下。
1。 服务票#452345: Lorem ipsum dolor sit amet,consectetur adipiscing elit,sed do eiusmod tempor incididunt ut 劳伦和多洛尔麦格纳阿尔夸。
服务票证部分以粗体和斜体显示,并且描述仅用斜体显示。服务票证编号和说明来自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
这使得服务故障单部分和描述变为粗体和粗体,因为选择应用于整个部分。我如何只保留第一部分粗体和斜体,另一部分只是粗体?
答案 0 :(得分:1)
请勿与Selection
合作,而是使用Range
,与在Excel中一样。
目标Word文档中的选择来自何处尚不清楚,因此我没有选择将其作为起点。但是,如果目标是由用户选择的话,通常你只会使用这种技术......
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
注意:您应该为此格式创建/使用字符样式,而不是直接应用格式。这样可以产生更高效的代码和更易于管理的文档。
答案 1 :(得分:1)
您可以使用“范围字符”属性格式化单元格中的特定字符。 (见https://msdn.microsoft.com/en-us/library/office/ff198232.aspx) 例如,以下例程将斜体显示并使所有文本加粗,并包括该范围中每个单元格的搜索字符串。在这种情况下,被搜索的字符串也作为参数传递。
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
答案 2 :(得分:0)
使用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
答案 3 :(得分:0)
这不优雅,但我做到了。
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