在所选单元格上使用For循环

时间:2014-06-04 02:29:37

标签: excel excel-vba vba

这是来自波士顿的莫妮克。 我创建了一个在一行上运行良好的VBA脚本。现在我希望在所有选定的行上实现它。

E.g。

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

但我一直遇到错误匹配错误。 我究竟做错了什么? 请帮帮我。

非常感谢你。 X

4 个答案:

答案 0 :(得分:1)

更直接

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

如果速度很重要,请使用变量数组

答案 1 :(得分:0)

尝试更改此内容:

For Each b In a.Rows
    'your code here
Next

到此:

For Each b In a
    'your code here
Next

您遇到类型不匹配的原因是因为a.Rows语法不正确;编译器不知道你指的是什么。有关Range.Rows媒体资源的详情,请查看this article

答案 2 :(得分:0)

除了ARich的回答,更改行

CostPrice = Range("C" & a).Value
Range("D" & a).Value = SellPrice

CostPrice = Range("C" & b.Row).Value
Range("D" & b.Row).Value = SellPrice

答案 3 :(得分:0)

删除此行Set a = Selection并添加以下行

Set a = Selection.Cells

希望有所帮助