picking number from a set of cells
Hello, I'm new to this site and new to VBA.
I need to write code in VBA that will do this:
If the number 1 is generated in cells B23 to B28, I need a 1 placed in B17. If 1 isn't generated in cells B23 to B28, I need a zero placed in B17.
If 2 is generated in cells B23 to B28, I need a 1 placed in B18. If 2 isn't generated in cells B23 to B28, I need a zero placed in B18.
If 3 is generated in cells B23 to B28, I need a 1 placed in B19. If 3 isn't generated in cells B23 to B28, I need a zero placed in B19.
If 4 is generated in cells B23 to B28, I need a 1 placed in B20. If 4 isn't generated in cells B23 to B28, I need a zero placed in B20.
If 5 is generated in cells B23 to B28, I need a 1 placed in B21. If 5 isn't generated in cells B23 to B28, I need a zero placed in B21.
If 6 is generated in cells B23 to B28, I need a 1 placed in B22. If 6 isn't generated in cells B23 to B28, I need a zero placed in B22.
Re: picking number from a set of cells
Welcome to the forums! :wave:
I am assuming you want this code to run whenever a change is made to the worksheet?
If so, copy the attached code into the Code page for the sheet in question.
VB Code:
Private Sub Worksheet_Change(ByVal Target As Range)
Dim MyRange As Range
Dim x As Integer
Dim Chk As Integer
Dim MyCell As Range
Set MyRange = Range("B23:B28") 'The range you need to check for your numbers
For x = 1 To 6 'Loop throught he numbers you want to check
Chk = 0 'assume the value is not found
For Each MyCell In MyRange 'Loop throught the cells in your range
If MyCell.Value = x Then
Chk = 1 'Find a match
Exit For 'don't need to look anymore
End If
Next MyCell
Application.EnableEvents = False 'Stops the Worksheet Change event from firing - which would cause an infinite loop
Range("B16").Offset(x, 0) = Chk 'record if the number is found
Application.EnableEvents = True 'Turn events back on
Next x
Set MyRange = Nothing
End Sub
Re: picking number from a set of cells
As a side note, you don't need to use VBA to achieve the results you want. You could just use the following formula in cell B17 and copy it down to fill the range B17:B22.
=IF(ISERROR(MATCH(A17,$B$23:$B$28,0)),0,1)
Note: I've assumed that you have labels of 1 to 6 in cells A17:A22. If this is not the case then change the reference A17 in the formula to the value that you want to check for in that cell.
Re: picking number from a set of cells
Thank you so much.
I really need to learn Excel better and I want to learn VB (and VBA). How do you suggest I start?
Again many thanks....