在excel宏中重复命令

时间:2015-12-18 07:10:49

标签: excel excel-vba vba

我想每隔15次在后续行中重复此命令。所以下一行将是J348:M348

SkipBlanks:=False, Transpose:=False
    Application.CutCopyMode = False
    Range("J318").Select
    ActiveCell.FormulaR1C1 = "=R303C10-((R3C2-R4C2)/(R5C2/R6C2))"
    Range("K318").Select
    ActiveCell.FormulaR1C1 = "=R303C11-((R3C3-R4C3)/(R5C2/R6C2))"
    Range("L318").Select
    ActiveCell.FormulaR1C1 = "=RC[-5]"
    Range("M318").Select
    ActiveCell.FormulaR1C1 = "=RC[-5]"
    Range("J318:M318").Select
    Selection.AutoFill Destination:=Range("J318:M332"), Type:=xlFillDefault
    Range("J318:M332").Select
    ActiveWindow.SmallScroll Down:=0
    Range("J332").Select
    ActiveWindow.SmallScroll Down:=15
    Range("J333:M333").Select
    Selection.Copy
    Range("J334").Select
    ActiveSheet.Paste
    Range("J335").Select
    Application.CutCopyMode = False
    Selection.Copy
    Range("J334:M334").Select
    Selection.PasteSpecial Paste:=xlPasteFormats, Operation:=xlNone, _

1 个答案:

答案 0 :(得分:0)

将代码直接迁移到循环代码:

我在第5行随机开始并使用了do while循环。您可以轻松使用for循环。希望这能让您了解循环,因此您不必手动完成。

Public Sub Every15thRow()

Dim i As Integer
Dim iFirst, iSecond, iThird, iFourth, iFifth As Integer
'in Ex: 318, 303, 332, 333, 334
Dim MyStopCriteria As Boolean
MyStopCriteria = False
'... whatever your code does before
'...

i = 5          'start with the 5th row

Do Until MyStopCriteria = True

    iFirst = i + 15
    iSecond = i
    iThird = i + 29
    iFourth = i + 30
    iFifth = i + 31

    Application.CutCopyMode = False
    Range("J" & iFirst).Select
    ActiveCell.FormulaR1C1 = "=R" & iSecond & "C10-((R3C2-R4C2)/(R5C2/R6C2))"
    Range("K" & iFirst).Select
    ActiveCell.FormulaR1C1 = "=R" & iSecond & "C11-((R3C3-R4C3)/(R5C2/R6C2))"
    Range("L" & iFirst).Select
    ActiveCell.FormulaR1C1 = "=RC[-5]"
    Range("M" & iFirst).Select
    ActiveCell.FormulaR1C1 = "=RC[-5]"
    Range("J" & iFirst & ":M" & iFirst).Select
    Selection.AutoFill Destination:=Range("J" & iFirst & ":M" & iThird), Type:=xlFillDefault
    Range("J" & iFirst & ":M" & iFourth).Select
    ActiveWindow.SmallScroll Down:=0
    Range("J" & iThird).Select
    ActiveWindow.SmallScroll Down:=15
    Range("J" & iThird & ":M" & iThird).Select
    Selection.Copy
    Range("J" & iFourth).Select
    ActiveSheet.Paste
    Range("J" & iFourth).Select
    Application.CutCopyMode = False
    Selection.Copy
    Range("J" & iFifth & ":M" & iFifth).Select

    '...
    '... whatever else your repeating code needs to do
    '...

    i = i + 15                          'Add 15 rows

    If i > 40 Then MyStopCriteria = True
Loop

    '... whatever else your code does after repeating

End Sub