Excel 在选定单元格上使用For循环

Excel 在选定单元格上使用For循环,excel,vba,Excel,Vba,我是波士顿的莫妮克。 我已经创建了一个VBA脚本,它在一行上运行良好。现在我想让它发生在所有选定的行上 例如 但我一直收到类型错误匹配错误。 我做错了什么? 请帮帮我 非常感谢你。x、 尝试更改此选项: For Each b In a.Rows 'your code here Next 为此: For Each b In a 'your code here Next 得到类型不匹配的原因是a.Rows的语法不正确;编译器不知道你指的是什么。查看范围.Rows属性的更多信息。除

我是波士顿的莫妮克。 我已经创建了一个VBA脚本,它在一行上运行良好。现在我想让它发生在所有选定的行上

例如

但我一直收到类型错误匹配错误。 我做错了什么? 请帮帮我

非常感谢你。x、 尝试更改此选项:

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

For Each b In a
    'your code here
Next

得到类型不匹配的原因是
a.Rows
的语法不正确;编译器不知道你指的是什么。查看
范围.Rows
属性的更多信息。

除了ARich的答案之外,还可以更改行

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


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

Set a = Selection.Cells
希望它能更直接地帮助你

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
如果速度很重要,则改为使用变量数组

Set a = Selection.Cells
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