Excel VBA:迭代范围参数并更改单元格值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12734949/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-11 18:00:06  来源:igfitidea点击:

Excel VBA: Iterating over range parameter and change cell values

excelvbaexcel-vba

提问by stevebot

I believe what I am trying to do is pretty simple. I want to iterate over a Range parameter and change the value for each cell in that range.

我相信我想要做的很简单。我想遍历 Range 参数并更改该范围内每个单元格的值。

Function test(thisRange As Range)
    For Each c In thisRange.Cells
         c.Value = 1
    Next
End Function

The above is a simple example of what I want to do, but doesn't seem to work. When I debug this, Excel seems to be throwing an error when it hits c.Value = 1. Why does this not work?

以上是我想做的一个简单示例,但似乎不起作用。当我对此进行调试时,Excel 似乎在遇到c.Value = 1. 为什么这不起作用?

采纳答案by Siddharth Rout

This works for me

这对我有用

Option Explicit

Sub Sample()
    Dim ret
    ret = test(Sheets("Sheet1").Range("A1:A15"))
End Sub

Function test(thisRange As Range)
    Dim c As Range
    For Each c In thisRange.Cells
         c.Value = 1
    Next
End Function

BTW we don't need to use a Function. A function is used to return a value. Try this

顺便说一句,我们不需要使用函数。函数用于返回值。尝试这个

Option Explicit

Sub Sample()
    test Sheets("Sheet1").Range("A1:A15")
End Sub

Sub test(thisRange As Range)
    Dim c As Range
    For Each c In thisRange.Cells
         c.Value = 1
    Next
End Sub