在选定单元格上使用For循环
这是来自波士顿的Monique。 我创build了一个VBA脚本,在一行上运行良好。 现在我想在所有选定的行上进行操作。
例如
Sub AutoButton_click() Dim a As Range, b As Range Set a = Selection For Each b In a.Rows Dim SellPrice As Double, CostPrice As Double CostPrice = Range("C" & a).Value SellPrice = CostPrice + 20 Range("D" & a).Value = SellPrice Next End Sub
但我不断收到types错误匹配错误。 我究竟做错了什么? 请帮帮我。
非常感谢。 X。
更直接
Sub AutoButton_click() Dim rng1 As Range For Each rng1 In Selection.Cells Cells(rng1.Row, "D").Value = Cells(rng1.Row, "c") + 20 Next End Sub
如果速度很重要,请使用变体数组来代替
尝试改变这一点:
For Each b In a.Rows 'your code here Next
对此:
For Each b In a 'your code here Next
你得到一个types不匹配的原因是因为a.Rows
是不正确的语法; 编译器不知道你指的是什么。 看看这篇文章 ,了解Range.Rows
属性的更多信息。
除了ARICH的答案,改变线
CostPrice = Range("C" & a).Value Range("D" & a).Value = SellPrice
至
CostPrice = Range("C" & b.Row).Value Range("D" & b.Row).Value = SellPrice
删除这一行Set a = Selection
并添加下面的行
Set a = Selection.Cells
希望能帮助到你