2014-07-23 26 views
0

我需要通过Excel宏将两个不同的文本部分自动插入到新生成的文件中。这是我的代码的一个例子。在Excel中为Word文件创建VBA中的Tabstops

首先我清除所有现有的标签以获得一个干净的文档,然后我想把“这个文本应该在左边对齐”和左边对齐,并且“这个文本应该在右边对齐”与右边对齐在同一行上。

.Content.Paragraphs.TabStops.ClearAll 
.Content.InsertAfter "This text should be aligned on the left" 

.Content.Paragraphs.TabStops.Add Position:=NewPos, _ 
     Alignment:=wdAlignTabRight, _ 
     Leader:=wdTabLeaderLines 

.Content.InsertAfter "This text should be aligned on the right" 
.Content.InsertParagraphAfter 

使用此命令我设法生成Word中的制表位,但我似乎不能够进行定位,或使右对齐“这段文字应该在右对齐”。

最后,它应该是这样的:

两个文本部分应当由VBA生成并对准这样。

picture

回答

1

是下面的代码为你工作?

Sub AlignLeftAndRight() 
    Selection.ParagraphFormat.TabStops.Add Position:=CentimetersToPoints(16) _ 
     , Alignment:=wdAlignTabRight, Leader:=wdTabLeaderSpaces 
    Selection.TypeText Text:="This text should be aligned on the left" 
    Selection.EndKey Unit:=wdLine 
    Selection.TypeText Text:=vbTab & "This text should be aligned on the right" 
End Sub 
+0

感谢您的快速回答。每当我尝试启动它时,都会收到错误消息“编译错误:子或功能未定义”。之后,CentimetersToPoints将突出显示。 – martiong

+0

至少该子过程适用于Word 2010.您使用的是哪个版本? – Kokkie

+1

旧线程,但对于那些找到它的人,CentimetersToPoints不是Excel 2007的一部分(至少在我的安装中),但如果你谷歌“厘米点”,你会发现因子是28.3464567,所以你可以用CentimetersToPoints(16) 16 * 28.3464567或编写您自己的转换功能。 – buttonsrtoys