为什么第一个问题的for循环没有继续?

时间:2017-07-21 12:22:20

标签: vba word-vba

我一直在构建一个代码,用于将数据从excel传输到word。为了尝试这一点,我已经构建了一个带有数组列表的代码。检查单词中的每个数组并在列表旁边放置一个字符串。但它没有把数组放在循环中。

Sub CreateNewWordDoc()

    Dim wrdApp As Word.Application
    Dim wrdDoc As Word.Document
    Dim i As Integer
    Dim arr(12)

    arr(0) = "(249_L), 38,7 %"
    arr(1) = "(248_R), 38,7 %"
    arr(2) = "(249_M), 38,7 "
    arr(3) = "(3560), 38,7 "
    arr(4) = "(3550), 38,7 %"
    arr(5) = "(349_), 38,7 %"
    arr(6) = "(348_), 38,7 %"
    arr(7) = "(451), 38,7 %"
    arr(8) = "(450L), 38,7 "
    arr(9) = "(450R), 38,7 "
    arr(10) = "(151), 38,7 %"
    arr(11) = "(150L), 38,7 %"
    arr(12) = "(150R), 38,7 %"

    Set wrdApp = CreateObject("Word.Application")

    wrdApp.Visible = True
    Set wrdDoc = wrdApp.Documents.Open("E:\ShareDrive_Ruehl\full-flexible-MBS-models_report\example-report\FullFlexibleGearbox - Copy (2).docx")


    For i = 0 To 12


    wrdDoc.Application.Selection.Find.Text = arr(i)
    wrdDoc.Application.Selection.Find.Execute
    wrdDoc.Application.Selection.InsertBefore arr(i) & "test"

    Next
    End Sub

我正在获得输出,如图所示。我的目的是找到" arr(i)"并在其前面放置arr(i)文字。但它只是找到array (0)并粘贴arr(i)文字。

enter image description here

1 个答案:

答案 0 :(得分:1)

这是您稍微调整过的代码。请注意使用With块进行稍微清理"清理"看看,HomeKey在下次查找之前重置选择:

Dim wrdApp As Word.Application
Dim wrdDoc As Word.Document
Dim i As Integer
Dim arr(12)

arr(0) = "(249_L), 38,7 %"
arr(1) = "(248_R), 38,7 %"
arr(2) = "(249_M), 38,7 "
arr(3) = "(3560), 38,7 "
arr(4) = "(3550), 38,7 %"
arr(5) = "(349_), 38,7 %"
arr(6) = "(348_), 38,7 %"
arr(7) = "(451), 38,7 %"
arr(8) = "(450L), 38,7 "
arr(9) = "(450R), 38,7 "
arr(10) = "(151), 38,7 %"
arr(11) = "(150L), 38,7 %"
arr(12) = "(150R), 38,7 %"
Set wrdApp = CreateObject("Word.Application")
Set wrdDoc = wrdApp.Documents.Open("E:\ShareDrive_Ruehl\full-flexible-MBS-models_report\example-report\FullFlexibleGearbox - Copy (2).docx")
wrdDoc.Activate
wrdApp.Selection.HomeKey unit:=wdStory

For i = 0 To 12
    With wrdApp.Selection
        With .Find
            .ClearFormatting
            .MatchWildcards = False
            .MatchWholeWord = False
            .text = arr(i)
            .Execute
        End With
        .InsertBefore arr(i) & "test"
        .HomeKey unit:=wdStory
    End With
Next

注意:很可能在不使用Selection的情况下实现您的需求,但需要进一步的信息。