如何在循环遍历一系列单元格时获取当前单元格编号 (Excel VBA)

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18760749/
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 23:17:10  来源:igfitidea点击:

How do I get the current cell number whilst looping through a range of cells (Excel VBA)

excelvba

提问by saintybalboa

I'm trying to get the current cell number whilst looping through a range of cells.

我试图在循环遍历一系列单元格的同时获取当前单元格编号。

For Each i In Sheet3.Range("A3:A213")

  msgbox(Sheet3.Range("B"&currentcellnumberinloop).Value)

Next

The purpose of this is to retrieve a value from another cell in the same row e.g. A1 and B1.

这样做的目的是从同一行中的另一个单元格(例如 A1 和 B1)中检索值。

采纳答案by saintybalboa

The iis probably declared as Range object(or Variant). Therefore to get the row number and retrieve the value in neighboring Bcolumn you have to call the .Rowmethod of the iobject

i可能是声明为Range对象(或变体)。因此,要获取行号并检索相邻B列中的值,您必须调用对象的.Row方法i

Sub ForEachAndFor()

    Dim i As Range

    For Each i In Sheet3.Range("A3:A213")
        MsgBox Sheet3.Range("B" & i.Row).Value
    Next

End Sub

You could also use the Offset(how_many_rows_up_or_down, how_many_columns_left_or_right)

你也可以使用 Offset(how_many_rows_up_or_down, how_many_columns_left_or_right)

you indicate rows down with a positive number an rows up with a negative number

你用正数表示向下的行,用负数表示向上的行

same applies to the columns, use -to navigate to the left of the current cell, and positive number to the right of the current cell.

同样适用于列,用于-导航到当前单元格的左侧,以及当前单元格右侧的正数。

Sub ForEachSub()

    Dim i as Range

    For Each i in Sheet3.Range("A3:A213")
        MsgBox i.Offset(0, 1).Value
    next i 

End Sub

回答by Vinny

Try this

尝试这个

Dim i as Integer

    For Each i In Sheet3.Range("A3:D213").Rows.Count
     msgbox(Sheet3.Range("B" & i).Value)
    Next i

回答by GrzMat

In your code variable i is of a Range type, thus you have to treat it that way. You can use Offset to get to what is in relation to your i address, like that:

在您的代码变量中, i 是 Range 类型,因此您必须这样对待它。您可以使用 Offset 来获取与您的 i 地址相关的内容,如下所示:

For Each i In Sheet3.Range("A3:A213")

  MsgBox (i.Offset(0, 1).Value)

Next i