简体   繁体   English

如何使用VBA浏览选定范围内的每一行

[英]How to go through each row within a selected range using VBA

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. 例如,选择了A6:B9,首先我要关注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. 如我希望能够使用我的MinSelected函数(如下所述)找到两个单元格的最小值,这需要一个选定的范围,理想情况下应为A6:B6。 And I want to do this for each row until the end of the original range. 我想对每一行执行此操作,直到原始范围结束。

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. 提前致谢。

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 VBA excel:对于Each..Next不会通过选定的范围? - VBA excel: For Each..Next doesn't go through the selected Range? 如何遍历范围对象 VBA 的每一行中的特定列? - How to loop through a specific column in each row for a range object VBA? 使用VBA从表中选定范围内的每个单元格中获取行号? - Get Row number from each cell in selected range in Table with VBA? 从VBA中的用户输入范围循环遍历每一行 - Loop through each row from a user input range in VBA excel vba选择行中的值,为每个值选择 - excel vba select value in row, which was selected through for each 在vba中使用带有多个条件的if语句循环遍历给定范围内的每一行 - loop through each row in a given range with if statement with multiple conditions in vba 如何编写一个 VBA 代码,该代码将循环遍历固定范围并在另一张表中将该范围的每一行填充 N 次(带编号)? - How to write a VBA code that will loop through a fixed range and populate each row of that range N times (with numbering) in another sheet? 如何使用VBA获取选定单元格的范围? - How to get the range of selected cells using VBA? 如何使用VBA对选定范围的列求和? - How to sum columns for a selected range using VBA? 如何使用 VBA 更新循环内的范围 - How to Update Range within a Loop using VBA
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM