如何将循环计数器重置为每一行?

How can I reset the loop counter to each rows?

我是 VBA 的新手。我正在创建一个程序,它将根据 table (Cell3Text) 的第 3 个 Cell 的值附加图像。 Cell3Text对应"images"文件夹中图片文件的文件名。例如,第一行的 15-00115-001r1.jpg, 15-001r2.jpg15-001r3.jpg、..等等。每行有不同数量的图像文件(*r1、*r2、*r3)。

我这里有使用循环的文件计数器。但在下一行,计数器会添加到前一行的计数中。如何将循环计数器重置为每一行?

Sub ContinuousCounter()

Set tbl = ActiveDocument.Tables(1)

Dim Cell3Text As String
Dim Cell1Text As String
   Dim imgDir As String
   Dim receiptsImg As String
   Dim count As Integer

For Idx = tbl.Rows.count To 1 Step -1
    tbl.Cell(Idx, 1).Range.Select

    Cell3Text = tbl.Cell(Idx, 3)
    Cell3Text = Left$(Cell3Text, Len(Cell3Text) - 2) ' Remove table cell markers from the text.
    Cell1Text = tbl.Cell(Idx, 1)
    Cell1Text = Left$(Cell1Text, Len(Cell1Text) - 2) ' Remove table cell markers from the text.
    imgDir = ActiveDocument.path & "\images\"
    receiptsImg = Dir(imgDir & Cell3Text & "r*.jpg")

    Selection.EndKey Unit:=wdRow, Extend:=True
    Selection.MoveRight Unit:=wdCharacter, count:=2

    If Len(Cell3Text) = 6 And receiptsImg <> "" Then


        While receiptsImg <> ""
            count = count + 1
           Selection.TypeText Text:=Chr(11)
           Selection.InlineShapes.AddPicture _
             FileName:=imgDir & receiptsImg, _
             LinkToFile:=False, SaveWithDocument:=True
             Selection.TypeText Text:=Chr(11)
           ' Get next file name.
           receiptsImg = Dir()
        Wend
        MsgBox count 'debugger only. shows the number of files containing "r" according to 3rd cell in a row
                    ' but seems every loop adds to the previous count
    Else

      MsgBox "No scanned image for " & Cell3Text & ". otherwise it is improperly renamed."

    End If



 ' ::::::::::::::::::::::::::::::::BREAK ROWS::::::::::::::::::::::::::::::::::::::::

    If Len(Cell3Text) < 2 Then ' if the 3rd cell is blank then turns into header
        tbl.Cell(Idx, 1).Select
        Selection.Rows.Delete
        Selection.InsertBreak Type:=wdColumnBreak  ' or Type:=wdPageBreak
        Selection.TypeText Cell1Text

    Else
        tbl.Cell(Idx, 1).Select
        Selection.Cells.Delete
        Selection.InsertBreak Type:=wdColumnBreak  ' or Selection.SplitTable

    End If

Next

End Sub

抱歉,如果我过于简单化了您的问题,您是否只需要执行以下操作:

If Len(Cell3Text) = 6 And receiptsImg <> "" Then

    count=0'Reset the counter for a new matching cell

    While receiptsImg <> ""
        count = count + 1
        ...
    Wend
    MsgBox count 'debugger only. shows the number of files containing "r" according to 3rd cell in a row
                ' but seems every loop adds to the previous count
Else

  MsgBox "No scanned image for " & Cell3Text & ". otherwise it is improperly renamed."

End If