VBA输出Array到Word文档的内容

时间:2016-09-25 18:04:37

标签: arrays vba word-vba

所以我需要做的是使用InputBox填充数组,然后在数组中,按字母顺序对其进行排序,然后将其输出到当前的word文档。我几乎是最完整的,问题是它只输出文档的最后一个字。我猜我的循环是错的,但我找不到VBA文档这样做来挽救我的生命。谢谢

Option Explicit

这是声明数组的主要子

Sub Main()

Dim ListArr() As String

ListArr = Get_Input_List()

Call Bubble_Sort_Ascending(ListArr)

Call Output_List_To_Document(ListArr)

End Sub

获取输入和填充数组的函数

Function Get_Input_List() As String()

Dim list As String

list = InputBox("Please enter words to sort separated with a comma and no spaces", "Words")
Get_Input_List = Split(list, ",")

End Function

按字母顺序对数组进行排序

Sub Bubble_Sort_Ascending(listNewArray() As String)

Dim SrtTemp As Variant
Dim inputWord As Variant
Dim i As Long
Dim j As Long

'Alphabetize Sheet Names in Array List
For i = LBound(listNewArray) To UBound(listNewArray)
     For j = i To UBound(listNewArray)
         If listNewArray(i) > listNewArray(j) Then
             SrtTemp = listNewArray(j)
             listNewArray(j) = listNewArray(i)
             listNewArray(i) = SrtTemp
         End If
     Next j
 Next i


End Sub

这是问题,我无法将整个数组输出到word文档。我已经找到了大量关于如何在excel电子表格中执行此操作的文档,但几乎没有任何消息。

Sub Output_List_To_Document(newListArray() As String)

Dim inputWord As Variant
Dim i As Long
Dim j As Long

For i = LBound(newListArray) To UBound(newListArray)
     For j = i To UBound(newListArray)
        For Each inputWord In newListArray
            ActiveDocument.Range = inputWord & vbCrLf
        Next
    Next j
Next i

End Sub

1 个答案:

答案 0 :(得分:2)

每次循环都会覆盖ActiveDocument.Range。如果要追加到它的末尾,则需要将范围折叠到它的结束位置:

Sub Output_List_To_Document(newListArray() As String)
    Dim inputWord As Variant
    Dim i As Long
    Dim j As Long

    Dim insertPos As Range
    Set insertPos = ActiveDocument.Range

    For i = LBound(newListArray) To UBound(newListArray)
         For j = i To UBound(newListArray)
            For Each inputWord In newListArray
                insertPos.Collapse wdCollapseEnd
                insertPos = inputWord & vbCrLf
            Next
        Next j
    Next i
End Sub

注意 - 目前尚不清楚为什么要使用3个嵌套循环遍历数组。如果你只需要写一次单词,我怀疑你真的正在寻找更像这样的东西:

Sub Output_List_To_Document(newListArray() As String)
    Dim insertPos As Range
    Set insertPos = ActiveDocument.Range

    Dim inputWord As Variant
    For Each inputWord In newListArray
        insertPos.Collapse wdCollapseEnd 'Value 0, Can ignore writing it as well
        insertPos = inputWord & vbCrLf
    Next
End Sub