我的代码“vba”出了什么问题

时间:2016-12-24 18:12:42

标签: vba if-statement

当我运行代码时,它生成一个介于100和210之间的随机数,我希望我的j值如下,但不会发生这种情况。

它为j生成数字,但不符合我编码的条件。

    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

1 个答案:

答案 0 :(得分:1)

已修改添加veeery短替代方案(请参阅答案底部)

它是因为您自动计算,在Range("I12").Value = j语句后,工作表会被计算,并且您在J12中放入的RANDBETWEEN()公式会重新计算,因此您不会看到它与你在I12之前写过j这样的最后一次重新计算

你可以使用这个

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通过以下代码实现了相同的结果

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