Sub ButtonLower()
Range("b2", "b7").Value = Range("b2", "b7").Value - 2
End Sub
Sub ButtonHigher()
Range("b2", "b7").Value = Range("b2", "b7").Value + 2
End Sub
最终结果是仅B2
的值更改,而不是整个范围更改。有人可以帮我吗?
答案 0 :(得分:2)
您不能直接对整个数组进行数学运算。使用评估:
With ActiveSheet.Range("B2:B7")
.Value = ActiveSheet.Evaluate(.Address & " - 2")
End With
和
With ActiveSheet.Range("B2:B7")
.Value = ActiveSheet.Evaluate(.Address & " + 2")
End With
或者您可以将整体加载到变量数组中并循环该数组:
Sub ButtonLower()
Dim arr() As Variant
arr = ActiveSheet.Range("b2:b7").Value
Dim i As Long
For i = LBound(arr, 1) To UBound(arr, 1)
Dim j As Long
For j = LBound(arr, 2) To UBound(arr, 2)
arr(i, j) = arr(i, j) - 2
Next j
Next i
ActiveSheet.Range("b2:b7").Value = arr
End Sub
答案 1 :(得分:2)
如果您要在A1中添加或减去值,则可以复制A1并将其添加到“范围”单元格中。
或者您可以使用循环。
Sub AddVal()
Range("A1").Copy
Range("B2:B7").PasteSpecial Paste:=xlPasteAll, Operation:=xlAdd, SkipBlanks:= _
False, Transpose:=False
Application.CutCopyMode = False
End Sub
Sub SubVal()
Range("A1").Copy
Range("B2:B7").PasteSpecial Paste:=xlPasteAll, Operation:=xlSubtract, SkipBlanks:= _
False, Transpose:=False
Application.CutCopyMode = False
End Sub
Sub LoopIt()
For Each cell In Range("B2:B7")
cell.Value = cell.Value + 2
Next
End Sub