• Describing values in ‘If’ statements (VBA Excel 2000)

    Home » Forums » AskWoody support » Productivity software by function » Visual Basic for Applications » Describing values in ‘If’ statements (VBA Excel 2000)

    Author
    Topic
    #407344

    I created the following “If” statement to do something if a value either = 0 or does not = 0. I would like to change this to say “If the value is between -2 and + 2, then do something. What can I substitue in my expression?
    Thanks.
    If Range (“Prncode”).Value = 0 Then
    Print2
    ElseIf Range(“Prncode”).Value 0 Then
    Print3

    Viewing 4 reply threads
    Author
    Replies
    • #851287

      You could use Select Case instead of If/Else. Example:

      Sub TestSub()

      Dim n As Long
      For n = -10 To 10
      Select Case n
      Case -2 To 2
      Debug.Print n, "True"
      Case Else
      Debug.Print n, "False"
      End Select
      Next n

      End Sub

      Test results:

      -10 False
      -9 False
      -8 False
      -7 False
      -6 False
      -5 False
      -4 False
      -3 False
      -2 True
      -1 True
      0 True
      1 True
      2 True
      3 False
      4 False
      5 False
      6 False
      7 False
      8 False
      9 False
      10 False

      You should be able to adapt this for your project.

      HTH

    • #851288

      You could use Select Case instead of If/Else. Example:

      Sub TestSub()

      Dim n As Long
      For n = -10 To 10
      Select Case n
      Case -2 To 2
      Debug.Print n, "True"
      Case Else
      Debug.Print n, "False"
      End Select
      Next n

      End Sub

      Test results:

      -10 False
      -9 False
      -8 False
      -7 False
      -6 False
      -5 False
      -4 False
      -3 False
      -2 True
      -1 True
      0 True
      1 True
      2 True
      3 False
      4 False
      5 False
      6 False
      7 False
      8 False
      9 False
      10 False

      You should be able to adapt this for your project.

      HTH

    • #851391

      if you only need to execute the same code if the value falls between these ranges, you could do the following

      If Range (“Prncode”).Value >=-2 and Range (“Prncode”).Value <=2 then
      'do something
      end if

    • #851392

      if you only need to execute the same code if the value falls between these ranges, you could do the following

      If Range (“Prncode”).Value >=-2 and Range (“Prncode”).Value <=2 then
      'do something
      end if

    • #851531

      If Pincode is always an integer then Select Case is probably the way to go. If it could have a value such as -1.7 then you will need to use a syntax such as pieter has suggested in post 389335

      StuartR

    Viewing 4 reply threads
    Reply To: Describing values in ‘If’ statements (VBA Excel 2000)

    You can use BBCodes to format your content.
    Your account can't use all available BBCodes, they will be stripped before saving.

    Your information: