简体   繁体   English

我的代码“ vba”有什么问题

[英]What is wrong with my code “vba”

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. 当我运行代码时,它将生成一个介于100和210之间的随机数,并且我希望j值如下所示,但是不会那样发生。

It generates numbers for j but it not according to conditions that I coded. 它为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

edited to add a veeery short alternative (see bottom of the answer) 编辑后添加veerery简短替代(请参见答案底部)

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 这是因为您具有自动计算功能,并且在Range("I12").Value = j语句之后,将对工作表进行计算,并且重新计算了您在J12中放入的RANDBETWEEN()公式,因此您看不到它与您先前在I12中编写的j匹配最后一次重新计算

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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