VBAalignment某些文字离开?

我正在使用下面的代码来查找和replaceWord文档中的某些文本。

代码正在执行从Excel工作簿。

Sub Macro1() Dim app As Word.Application Dim doc As Word.Document Set app = CreateObject("Word.Application") app.Visible = True Set doc = app.Documents.Open("G:\QUALITY ASSURANCE\03_AUDITS\PAI\templates\Audit Announcement Template.docx") With doc.Range.Find .Text = "22nd May 2017" .Text = "Supplier Name" .Text = "The Address" .Text = "Audit Code Goes Here" .Text = "Production Site Address Goes Here" .Replacement.Text = DayString(Now()) & " " & Format(Now(), "mmmm yyyy") .Replacement.Text = Range("O" & ActiveCell.Row).Value .Replacement.Text = Replace(Range("P" & ActiveCell.Row).Value, ", ", Chr(11)) .Replacement.Text = Range("B" & ActiveCell.Row).Value & "_" & Range("C" & ActiveCell.Row).Value & "_" & Range("D" & ActiveCell.Row).Value & "_" & Range("E" & ActiveCell.Row).Value & "_" & Range("F" & ActiveCell.Row).Value & "_" & Range("G" & ActiveCell.Row).Value & "_" & Range("H" & ActiveCell.Row).Value .Replacement.Text = Replace(Range("P" & ActiveCell.Row).Value, ", ", Chr(11)) .objselection.Paragraphs.Alignment = 3 .Forward = True .Wrap = wdFindContinue .Format = False .MatchCase = False .MatchWholeWord = False .MatchWildcards = False .MatchSoundsLike = False .MatchAllWordForms = False .Execute Replace:=wdReplaceAll End With doc.SaveAs Filename:="G:\QUALITY ASSURANCE\03_AUDITS\PAI\templates\Audit Announcement Template2.doc", _ FileFormat:=wdFormatDocument doc.Close app.Quit End Sub Public Function DayString(ByVal pDate As Date) As String Dim intDay As Integer Dim strReturn As String intDay = Day(pDate) Select Case intDay Case 1, 21, 31 strReturn = intDay & "st" Case 2, 22 strReturn = intDay & "nd" Case 3, 23 strReturn = intDay & "rd" Case Else strReturn = intDay & "th" End Select DayString = strReturn End Function 

代码工作正常。

但是在这一行上:

 .Replacement.Text = Replace(Range("P" & ActiveCell.Row).Value, ", ", Chr(11)) 

正在插入文本有趣(半左alignment和右alignment)

在这里输入图像说明

我想要这样的文字是合理的:

在这里输入图像说明

我正在设置模板文字文本左alignment,但似乎正在改变这一点。

请有人告诉我我要去哪里错了吗? 请能有人

除了alignment常量的问题之外,最好使用单词中的“插入”function区来在模板文件中创build书签 。 这样,即使底层模板文本发生了变化,您的文档结构仍然存在,并且不需要更新代码(除非有人更改了书签的名称)。

在这里输入图像说明

然后使用书签分配文本:

 Dim doc As Word.Document Dim bk As Word.Bookmark Dim b As Variant Dim BOOKMARK_NAMES() BOOKMARK_NAMES = [{"AuditCode","SiteAddress"}] '## Modify as needed Set wd = GetObject(, "Word.Application") Set doc = wd.ActiveDocument For Each b In BOOKMARK_NAMES Set bk = doc.bookmarks(b) Select Case b Case "AuditCode" bk.Range.Text = Join(Application.Transpose(Application.Transpose(Range("A" & ActiveCell.Row).Resize(, 8))), "") Case "SiteAddress" bk.Range.Text = Replace(Range("P" & ActiveCell.Row).Value, ", ", Chr(11)) 'Etc... End Select Next 

导致:

在这里输入图像说明

据我可以告诉你正在使用

 .objselection.Paragraphs.Alignment = 3 

这是alignment你的文字,因为你想要它。 相反,这是一个合理的路线。 你想要的是:

 .objselection.Paragraphs.Alignment = 0 

要么

 .objselection.Paragraphs.Alignment = wdAlignParagraphLeft