简体   繁体   中英

How do I get the index in a VBA For Each Loop (programming with Excel)?

I am working with EXCEL VBA to process some data and here is what I want to make:

我想开发一个可以计算出浅绿色区域中的值的函数

In this sheet, I want to create a function "GetDebutDate" that can automatically calculate the first date that the row has a value.

For example, in the row of "Mark", the first time to get a value is Aug-05 with a number of "4".

I know few about VBA and after searching around I found I can use For ... Each to loop in a range. But how do I get the index of the "v" in each loop? After I get that index, how do I get the value of the Date in the head row?

Function Get_Board_Count(range As range)
  For Each v In range
    ....
  Next
  Get_Board_Count = ....
End Function
Function Get_Board_Count(range As range)
    dim i as integer
    i = 1

    for each v in Range
       ...
       i = i + 1
    next


  Get_Board_Count = i 'Index of the item where cell is found.
End Function

When using For Each , it's not a good idea to make any assumptions about the order in which you get the objects: it might change in subsequent Excel versions or even from session to session.

However, v is a reference to a range itself, so you have access to the properties and methods of Excel.Range via it. Use v.Column to extract the column to which a particular v is referring; which will be the column containing the corresponding date.

You can alternatively use an Excel-Only solution, which doesn't need VBA programming. Have a look a this formula:

=INDIRECT(ADDRESS(1,MATCH(TRUE,INDEX(A2:E2>0,0),0)))

MATCH(TRUE,INDEX(A2:E2>0,0),0) looks up the first value which is greater than 0 and not null and returns the current column index of this value. the rest of the formula refers to the row, with the dates, to get the wanted date per reference. In my case is it the first row...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM