【问题标题】:Word VBA placing text in a tableWord VBA 在表格中放置文本
【发布时间】:2015-06-27 06:47:43
【问题描述】:

我正在尝试在 MS Word 中的表格中放置文本,该表格由第一行和 2 列中的标题组成,然后是文本应该放在的另一行。

要填充表格的文本更准确地说是在 UserForm 中 TextBox3

所以如果 TextBox3 包含:

汽车注册服务经理

我希望表格如下所示:

 Header#1  | Header#2

Automotive | 85,000 
Registered | 77,000 
Services   | 32,000 
Manager    | 500,00

来自 Header#2 的数字来自 excel 的数据库,我可以决定手动执行或稍后处理,如果我遇到困难我会寻求帮助,但现在我正在努力解决的是表,因为我只有 1 行要粘贴信息,

我尝试使用:

Dim tmpArray As Variant
tmpArray = Split(TextBox3, " ")


Dim i As Integer
For i = 1 To UBound(tmpArray)

    ActiveDocument.Tables(1).Cell(i, 1).Range = tmpArray(i - 1)
    Selection.TypeParagraph



Next i

但即使我有TypeParagraph,代码也只写了第二个字,让我给你整个代码,看看我们能想出什么。

Private Sub CommandButton1_Click()
With ActiveDocument
    .Bookmarks("bmCN").Range _
    .InsertBefore TextBox1
    .Bookmarks("bmOriJob").Range _
    .InsertBefore TextBox2
    .Bookmarks("bmOptJob").Range _
    .InsertBefore TextBox3
    .Bookmarks("bmJobD").Range _
    .InsertBefore TextBox4
    .Bookmarks("bmJobRes").Range _
    .InsertBefore TextBox5
    .Bookmarks("bmJobR").Range _
    .InsertBefore TextBox6
    .Bookmarks("bmBen").Range _
    .InsertBefore TextBox7
    .Bookmarks("bmTag").Range _
    .InsertBefore TextBox8
End With
'Temporary array
Dim tmpArray As Variant
    tmpArray = Split(TextBox3, " ")


Dim i As Integer
For i = 1 To UBound(tmpArray)

    ActiveDocument.Tables(1).Cell(i, 1).Range = tmpArray(i - 1)
    Selection.TypeParagraph



Next i
UserForm1.Hide
    Selection.WholeStory
    Selection.Fields.Update
    Selection.Collapse Direction:=wdCollapseEnd
End Sub

谢谢,

【问题讨论】:

    标签: vba ms-word


    【解决方案1】:

    问题在于循环中的数组索引。由于i 的最大值为UBound(tmpArray),并且您将单元格设置为tmpArray(i - 1),因此您将始终忽略最后一个数组元素。您还从标题行开始(Cell(1, 1) 第一次通过循环)。最后,直接使用文档的 Range 对象不会影响选择了哪个 Range,因此 Selection.TypeParagraph 将始终位于运行代码之前选择的任何位置。因为这是在你的循环中,我猜这不是想要的行为。最后,您可能应该在第一时间获取对 ActiveDocument 的引用,并根据需要在 Subs 之间传递它。它不仅比不断取消引用全局更有效,而且避免了在代码运行时用户交互可能更改活动文档的情况。

    这样的事情应该可以工作:

    Dim doc As Document
    Set doc = ActiveDocument
    
    '...
    
    Dim tmpArray As Variant
    tmpArray = Split(TextBox3.Text, " ")
    
    Dim i As Integer
    For i = 0 To UBound(tmpArray)
        doc.Tables(1).Cell(i + 2, 1).Range = tmpArray(i)
    Next i
    

    【讨论】:

    • 嗨@Comintern 试过了,但它不起作用我得到了同样的行为,只是最后一个字留在了表格中
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多