如何循环一个现有的宏?

时间:2019-04-19 15:57:34

标签: vba ms-word word-vba repeat

我在MS Word中有一个表,该表是2列乘1000行。我做了一个宏,按顺序

  1. 在当前行下方添加新行
  2. 合并新行中的两个单元格
  3. 将上方单元格中的文本剪切并粘贴到新行中,
  4. 将图像移动到一列,然后
  5. 将文本添加到单元格。完成事件字符串后,光标就可以再次执行所有操作。

没有任何条件可以在运行时将其弄乱(例如,空单元格等),我不需要代码来查找特定的东西,只需要重复它即可。

我需要在现有代码中添加些什么,以使其重复到文档末尾(具体是1000次)。

我看过Excel的代码,但是我没有看过在Word中浏览表格的代码。

Selection.MoveDown Unit:=wdParagraph, Count:=2, Extend:=wdExtend
Selection.InsertRowsBelow 1
Selection.MoveDown Unit:=wdLine, Count:=1
Selection.MoveUp Unit:=wdLine, Count:=1
Selection.MoveDown Unit:=wdParagraph, Count:=2, Extend:=wdExtend
Selection.Cells.Merge
Selection.MoveUp Unit:=wdLine, Count:=1
Selection.MoveDown Unit:=wdParagraph, Count:=1, Extend:=wdExtend
Selection.Cut
Selection.MoveDown Unit:=wdLine, Count:=1
Selection.PasteAndFormat (wdPasteDefault)
Selection.Font.Size = 4
Selection.MoveUp Unit:=wdLine, Count:=1
Selection.MoveRight Unit:=wdCharacter, Count:=1
Selection.MoveRight Unit:=wdCharacter, Count:=1, Extend:=wdExtend
Selection.Cut
Selection.MoveLeft Unit:=wdCharacter, Count:=1
Selection.PasteAndFormat (wdPasteDefault)
Selection.MoveRight Unit:=wdCharacter, Count:=1
Selection.Font.Size = 3
Selection.TypeText Text:="Unique specimen identifier not a property tag"
Selection.MoveDown Unit:=wdLine, Count:=2
Selection.MoveLeft Unit:=wdCharacter, Count:=2, Extend:=wdExtend
Selection.MoveLeft Unit:=wdCharacter, Count:=1

我希望能够运行一次代码,并使其重复执行直到到达文档末尾为止,并且如果可能的话,可以重复执行1000次。

我希望这不是太“广泛”,因为我有代码并在问一个特定的问题。

1 个答案:

答案 0 :(得分:1)

您可以通过将其包装到For...Next循环中来重复指令集,这在VBA应用程序中是相当标准的。这段代码创建了一个循环和一个'index'变量,然后告诉它精确地遍历该索引1000次。

For index As Integer = 1 To 1000
    Selection.MoveDown Unit:=wdParagraph, Count:=2, Extend:=wdExtend
    Selection.InsertRowsBelow 1
    Selection.MoveDown Unit:=wdLine, Count:=1
    Selection.MoveUp Unit:=wdLine, Count:=1
    Selection.MoveDown Unit:=wdParagraph, Count:=2, Extend:=wdExtend
    Selection.Cells.Merge
    Selection.MoveUp Unit:=wdLine, Count:=1
    Selection.MoveDown Unit:=wdParagraph, Count:=1, Extend:=wdExtend
    Selection.Cut
    Selection.MoveDown Unit:=wdLine, Count:=1
    Selection.PasteAndFormat (wdPasteDefault)
    Selection.Font.Size = 4
    Selection.MoveUp Unit:=wdLine, Count:=1
    Selection.MoveRight Unit:=wdCharacter, Count:=1
    Selection.MoveRight Unit:=wdCharacter, Count:=1, Extend:=wdExtend
    Selection.Cut
    Selection.MoveLeft Unit:=wdCharacter, Count:=1
    Selection.PasteAndFormat (wdPasteDefault)
    Selection.MoveRight Unit:=wdCharacter, Count:=1
    Selection.Font.Size = 3
    Selection.TypeText Text:="Unique specimen identifier not a property tag"
    Selection.MoveDown Unit:=wdLine, Count:=2
    Selection.MoveLeft Unit:=wdCharacter, Count:=2, Extend:=wdExtend
    Selection.MoveLeft Unit:=wdCharacter, Count:=1
Next

如果您需要无限次地循环某事(例如,当满足特定条件时),则可以使用Do...WhileDo...Until循环。