Excel宏 - 重复一个过程

时间:2016-04-14 14:25:01

标签: excel vba excel-vba macros

我有一个录制的宏,用于Excel中的简单处理。但是,我需要它重复大约80行的过程。这是我前4行的代码。任何有关这种简单方法的帮助都将受到赞赏。谢谢。

Sub Macro2()
'
' Macro2 Macro
'

'
Range("A5").Select
ActiveCell.FormulaR1C1 = "1"
Sheets("EST COST").Select
Range("D6").Select
Selection.Copy
Sheets("IL").Select
Range("I5").Select
Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
    :=False, Transpose:=False
Range("A5").Select
ActiveCell.FormulaR1C1 = "0"

Range("A6").Select
ActiveCell.FormulaR1C1 = "1"
Sheets("EST COST").Select
Range("D6").Select
Selection.Copy
Sheets("IL").Select
Range("I6").Select
Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
    :=False, Transpose:=False
Range("A6").Select
ActiveCell.FormulaR1C1 = "0"

Range("A7").Select
ActiveCell.FormulaR1C1 = "1"
Sheets("EST COST").Select
Range("D6").Select
Selection.Copy
Sheets("IL").Select
Range("I7").Select
Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
    :=False, Transpose:=False
Range("A7").Select
ActiveCell.FormulaR1C1 = "0"
End Sub

3 个答案:

答案 0 :(得分:2)

你想使用for ... next循环。一些谷歌搜索应该让你走得很远,但这里有一个大致的想法:

dim startRow as integer
dim endRow as integer
dim myColumn as integer

startRow = 5
endRow = 45
For activeRow = startRow to endRow
    [do something]
    myColumn = [some column number]
    cells(activeRow, myColumn).Value = [something]
Next activeRow

答案 1 :(得分:0)

像这样的东西

def create
  #this returns true or false
  if User.exists?(email: params[:email])
    flash[:notice] = "Email address already in use!"
    redirect_to new_merchant_path
  else
    render 'form'
  end
end

答案 2 :(得分:0)

要保持代码与您的代码相似,请尝试以下操作:

Sub test()
Dim rng As Range
Dim i&

For i = 5 To 40
' WHAT SHEET IS YOUR DEFAULT RANGES ON?
Range("A" & i).FormulaR1C1 = "1" ' what sheet is this on? We want to be explicit
Sheets("EST COST").Range("D" & i + 1).Copy
Sheets("IL").Range("I" & i).PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
    :=False, Transpose:=False
Range("A" & i).FormulaR1C1 = "0"
Next i

End Sub

我假设您希望粘贴的范围偏移一行(您复制A5,粘贴到I6)。正如我所指出的,我更愿意知道要复制的范围是什么表,因此我们可以将该工作表添加到范围(Range("A"& i)...应该是Sheets("mainSheet").Range("A"&i)...