【发布时间】:2015-12-14 03:38:06
【问题描述】:
我是 VBA 新手。我正在创建一个程序,它将根据表的第三个Cell (Cell3Text) 的值附加图像。 Cell3Text 对应“images”文件夹中图像文件的文件名。比如第一行的15-001有15-001r1.jpg、15-001r2.jpg、15- 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
【问题讨论】: