When I run the code it generates a random number between 100 and 210 and I want my j
to be valued as follows but it is not happening like that.
It generates numbers for j
but it not according to conditions that I coded.
Range("J12").Formula = "=RANDBETWEEN(100,210)"
x = Range("J12").Value
If x < 109 And x >= 100 Then
j = 100
ElseIf x > 109 And x < 119 Then
j = 110
ElseIf x > 119 And x < 129 Then
j = 120
ElseIf x > 129 And x < 139 Then
j = 130
ElseIf x > 139 And x < 149 Then
j = 140
ElseIf x > 149 And x < 159 Then
j = 150
ElseIf x > 159 And x < 169 Then
j = 160
ElseIf x > 169 And x < 179 Then
j = 170
ElseIf x > 179 And x < 189 Then
j = 180
ElseIf x > 189 And x < 199 Then
j = 190
Else: j = 200
End If
Range("I12").Value = j
edited to add a veeery short alternative (see bottom of the answer)
it's because you have calculation automatic and after Range("I12").Value = j
statement the worksheets gets calculated and RANDBETWEEN()
formula you put in J12 gets recalculated and so you don't see it match the j
you wrote in I12 previously to such last recalculation
you may use this
Sub main()
Dim x As Long, j As Long
With Range("J12")
.Formula = "=RANDBETWEEN(100,210)"
.Value = .Value
Select Case .Value
Case 100 To 108
j = 100
Case 109 To 118
j = 110
Case 119 To 128
j = 120
Case 129 To 138
j = 130
Case 139 To 148
j = 140
Case 149 To 158
j = 150
Case 159 To 168
j = 160
Case 169 To 178
j = 170
Case 179 To 188
j = 180
Case 189 To 198
j = 190
Case Else
j = 200
End Select
End With
Range("I12").Value = j
End Sub
BTW the same results are achieved by the following code
Sub main()
With Range("J12")
.Formula = "=RANDBETWEEN(100,210)"
.Value = .Value
.Offset(, -1).Value = IIf(.Value > 208, 200, Int((.Value + 1 - 100) / 10) * 10 + 100)
End With
End Sub
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.