("vba & code")// counting cells

montecarlo2012

Well-known Member
Joined
Jan 26, 2011
Messages
985
Office Version
  1. 2010
Platform
  1. Windows
Hello.
Book1
BC
2011
32
43
54
65
79
87
98
109
112
123
134
145
159
167
178
Sheet1

In column B2 I have this array and in C the answer.
Trying to count how many cells are until a value is found.
this is the try:
VBA Code:
Sub Locat()
Set rngData = Range("b2:b25")
For Each cell In rngData
    If cell = 9 Then
        Range("c2").Value = n
          Else
       n = n + 1
    End If
Next
End Sub
if cell = 9 the answer expected on c2 is 6, if you count how many cells are until the ("first") 9 is founded, there are 6 places,
if cell = 2 the answer expected on c2 is 2
if cell = 0 the answer will be 1 etc.
but my snippet code give me the wrong count

Thank you for reading this, and will be nice some help.
 

Excel Facts

Move date out one month or year
Use =EDATE(A2,1) for one month later. Use EDATE(A2,12) for one year later.
Try this.
VBA Code:
Sub Locat()
    Set rngData = Range("b2:b25")
    For Each cell In rngData
        If cell = 9 Then
            n = n + 1
            Range("c2").Value = n
            Exit Sub
        Else
           n = n + 1
        End If
    Next
End Sub
 
Upvote 0
Solution
Input number into an inputbox then hit OK:

VBA Code:
Option Explicit
Sub Locat()
Range("c2").Value = Evaluate("=IFERROR(MATCH(" & InputBox("Which number?") & ",B2:B25, 0),""not exists!"")")
End Sub
 
Upvote 0
HongRu.
Thank you. is the solution, so I marked it. my concern is the logic behind, as a code, not a compact formula
 
Upvote 0

Forum statistics

Threads
1,223,708
Messages
6,174,005
Members
452,542
Latest member
Bricklin

We've detected that you are using an adblocker.

We have a great community of people providing Excel help here, but the hosting costs are enormous. You can help keep this site running by allowing ads on MrExcel.com.
Allow Ads at MrExcel

Which adblocker are you using?

Disable AdBlock

Follow these easy steps to disable AdBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the icon in the browser’s toolbar.
2)Click on the "Pause on this site" option.
Go back

Disable AdBlock Plus

Follow these easy steps to disable AdBlock Plus

1)Click on the icon in the browser’s toolbar.
2)Click on the toggle to disable it for "mrexcel.com".
Go back

Disable uBlock Origin

Follow these easy steps to disable uBlock Origin

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back

Disable uBlock

Follow these easy steps to disable uBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back
Back
Top