vba 如何使用VBA遍历选定范围内的每一行
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/28706329/
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
How to go through each row within a selected range using VBA
提问by hotkoreanchick
Ideally, I would have a range selected and then I would run the macro and I want the macro to essentially run a loop to go through each row so I can extract information from each row until it reaches the end of the range.
理想情况下,我会选择一个范围,然后运行宏,我希望宏基本上运行一个循环来遍历每一行,这样我就可以从每一行中提取信息,直到它到达范围的末尾。
For example, A6:B9 are selected, first I want to focus on A6:B6. As in I want to be able to find the min value of the two cells for instance, using my MinSelected function(stated below) which requires a selected range which would ideally be A6:B6. And I want to do this for each row until the end of the original range.
比如A6:B9被选中,首先我要关注A6:B6。例如,我希望能够找到两个单元格的最小值,使用我的 MinSelected 函数(如下所述),它需要一个选定的范围,理想情况下是 A6:B6。我想对每一行都这样做,直到原始范围结束。
Function MinSelected(R As Range)
MinSelected = Application.WorksheetFunction.min(R)
End Function
Is there any way to do this??? Please tell me to clarify anything that's unclear. Thanks in advance.
有没有办法做到这一点???请告诉我澄清任何不清楚的地方。提前致谢。
采纳答案by brettdj
You can loop through rows - but looping through a variant array is more efficient (for many rows)
您可以遍历行 - 但遍历变体数组效率更高(对于多行)
variant aray
变体阵列
Dim X
Dim lngCnt As Long
X = Range("A6:B9").Value2
For lngCnt = 1 To UBound(X)
Debug.Print Application.Min(Application.Index(X, lngCnt))
Next
range approach
范围方法
Dim rng1 As Range
Dim rng2 As Range
Set rng1 = Range("A6:B9")
For Each rng2 In rng1.Rows
Debug.Print Application.Min(rng2)
Next
回答by Jeanno
Use a For
loop, Rows.Count
property, Columns.Count
使用For
循环、Rows.Count
属性、Columns.Count
Dim i as long
For i = 1 to Selection.Rows.Count
For j = 1 To Selection.Columns.Count
Cells(i, j).Value ' Use this to access the value of cell in row i and column j