如何在 vba 中编写操作?
How can i write operation in vba?
大家好,我正在用vba做一个宏代码,想请教一下,如何通过vba宏来写下一个操作。
假设您有一个包含两列的 sheet,一列称为 "C",另一列称为 "D",并且此列中的每个单元格都有下一个操作:
ws.Range("D1") = 0
ws.Range("D2") = ws.Range(C2)- ws.Range(C1)
ws.Range("D3") = ws.Range(C3)- ws.Range(C2)
...
ws.Range(Di+1) = ws.Range(Ci+1) -ws.Range(Ci)
如何用 vba 语法编写如下操作:
ws.Range("D:D").FormulaR1C1 = "= R[i+1]C[""C""] - R[i]C[""C""]"
感谢您的帮助。
有很多选择。请参阅下面的代码示例(假设我正确理解您的要求)
Sub FillCells()
Dim RangeToFill As Range
Dim CurCell As Range
Dim wks As Worksheet
Set wks = ActiveSheet
Set RangeToFill = wks.Range("D2:D8") ''' define the range as required or even better - use named ranges in the so
'''' Option 1
''' youcan use R1C1 reference style for the whole range - very fast and nice solution
RangeToFill.FormulaR1C1 = "=RC[1]-R[-1]C[1]"
'''' Option 2
''' or you can use .Offset property of the range object. Note that .Address(0,0) has two zeros for the cell address not to be frozen,
''' i.e. not =$E - $E but =E2-E1
''' This also works but could be slower on big ranges and formula looks pretty ugly to my taste
For Each CurCell In RangeToFill.Cells
CurCell.Formula = "=" & CurCell.Offset(0, 1).Address(0, 0) & "-" & CurCell.Offset(-1, 1).Address(0, 0)
Next CurCell
End Sub
大家好,我正在用vba做一个宏代码,想请教一下,如何通过vba宏来写下一个操作。
假设您有一个包含两列的 sheet,一列称为 "C",另一列称为 "D",并且此列中的每个单元格都有下一个操作:
ws.Range("D1") = 0
ws.Range("D2") = ws.Range(C2)- ws.Range(C1)
ws.Range("D3") = ws.Range(C3)- ws.Range(C2)
...
ws.Range(Di+1) = ws.Range(Ci+1) -ws.Range(Ci)
如何用 vba 语法编写如下操作:
ws.Range("D:D").FormulaR1C1 = "= R[i+1]C[""C""] - R[i]C[""C""]"
感谢您的帮助。
有很多选择。请参阅下面的代码示例(假设我正确理解您的要求)
Sub FillCells()
Dim RangeToFill As Range
Dim CurCell As Range
Dim wks As Worksheet
Set wks = ActiveSheet
Set RangeToFill = wks.Range("D2:D8") ''' define the range as required or even better - use named ranges in the so
'''' Option 1
''' youcan use R1C1 reference style for the whole range - very fast and nice solution
RangeToFill.FormulaR1C1 = "=RC[1]-R[-1]C[1]"
'''' Option 2
''' or you can use .Offset property of the range object. Note that .Address(0,0) has two zeros for the cell address not to be frozen,
''' i.e. not =$E - $E but =E2-E1
''' This also works but could be slower on big ranges and formula looks pretty ugly to my taste
For Each CurCell In RangeToFill.Cells
CurCell.Formula = "=" & CurCell.Offset(0, 1).Address(0, 0) & "-" & CurCell.Offset(-1, 1).Address(0, 0)
Next CurCell
End Sub