我的代码(如果语句返回错误的结果

时间:2018-06-14 06:24:59

标签: excel vba excel-vba

Sub redrer()
    Dim s As LongPtr
    Dim k As String
    Dim t As Integer
    Dim r As Long
    Worksheets("sheet3").Activate
    Range("B2").Select

    Do Until ActiveCell.Value = ""
        s = ActiveCell.Value
        k = ActiveCell.Offset(0, 1)
        t = ActiveCell.Offset(0, 2)
        r = ActiveCell.Offset(0, 3)

        If Len(k) = 2 And s > 15000 Or s < 35000 Then
            t = 10
        ElseIf Len(k) = 3 And s > 15000 Or s < 35000 Then
            t = 20
        Else
            t = 0
        End If

        If Len(k) = 2 And s > 35000 Or s < 75000 Then
            t = 44
        ElseIf Len(k) = 3 And s > 35000 Or s < 75000 Then
            t = 48
        Else
            t = 0
        End If

        ActiveCell.Offset(0, 2).Value = t
        ActiveCell.Offset(1, 0).Select
    Loop
End Sub
即使s在15000或35000之间,他仍然会返回t = 44或48 我做错了什么?

1 个答案:

答案 0 :(得分:2)

  1. 不要使用两个“如果不是”&#39;条件因为t的值总是替换为第二个&#39; if else&#39;条件,首先是“如果不是”&#39;条件是少用

  2. 使用&#39;和运营商&#39;检查以下代码:

    If Len(k) = 2 And s > 15000 and s < 35000 Then
        t = 10
    ElseIf Len(k) = 3 And s > 15000 and s < 35000 Then
        t = 20       
    ElseIf Len(k) = 2 And s > 35000 and s < 75000 Then
        t = 44
    ElseIf Len(k) = 3 And s > 35000 and s < 75000 Then
        t = 48
    Else
        t = 0
    End If
    
  3. 祝你好运:)