0
Dim HHs As String
HHs = Mid("2345", 1, 2)

If Val(HHs) > 23 Then
"Log the Error that needs to be logged"
End If

The above code is failing in the validation . This seems to be a very simple problem Any idea why?

rohit
  • 159
  • 12
  • Where is `MMs` assignment??? – LS_ᴅᴇᴠ Aug 29 '17 at 07:19
  • `HHe` is not the same variable as `HHs` - **Always** use `Option Explicit`, and you'll avoid these errors 99 times out of 100. – ThunderFrame Aug 29 '17 at 07:21
  • `"Log the Error that needs to be logged"` is not a valid statement. Did you perhaps mean `Debug.Print "Log the Error that needs to be logged"` or maybe `'Log the Error that needs to be logged`? – ThunderFrame Aug 29 '17 at 07:26
  • Your edit still isn't naming the variables correctly and consistently. PLEASE use Option Explicit - you'll do yourself a favor! `Dim HHs As String` – ThunderFrame Aug 29 '17 at 07:28
  • 1
    I don't have any error using visual basic 6. Are you using VBA? What si your Office version? – Pedro Polonia Aug 29 '17 at 07:58
  • 2
    After your edits which have invalidated most of the comments and some of the answers, I'm not seeing the problem. As [Pedro points out](https://stackoverflow.com/a/45933642/2344413), the left two characters of `2345` are `23`, which, when implicitly converted to a `Long`, are exactly equal to `23`. since `23 = 23` is `True`, you'll never drop into your `"Log error"` code. Therefore, you don't have a problem as your post stands at the moment. Please describe what behavior you're actually expecting. – FreeMan Aug 29 '17 at 12:08
  • If `2345` is supposed to represent a time and you're looking at the first two digits to determine if it is after 11pm, then use time formatting and don't try to deal with it as string information. – FreeMan Aug 29 '17 at 12:09
  • Val returns a double. It you're using VBA you might want to look at https://stackoverflow.com/questions/235409/compare-double-in-vba-precision-problem – Jim Hewitt Aug 30 '17 at 01:03
  • `Val()` is bad, m'kay? – Bob77 Aug 30 '17 at 23:53

2 Answers2

0

If HHs hasn't been declared (and you haven't used Option Explicit), or you haven't assigned a value to HHs, then Val(HHs) will always be 0....

As such, Val(HHs) > 23 will always be False.

It seems likely you made a typo, and meant to use HHe?

ThunderFrame
  • 9,352
  • 2
  • 29
  • 60
0

The code works as expected: the if condition is false since Val(HHs) is 23.

Option Explicit

Private Sub CommandTest_Click()
    Dim HHs As String
    HHs = Mid("2345", 1, 2)

    If Val(HHs) > 23 Then
        MsgBox "Log the Error that needs to be logged"
    End If
End Sub
Pedro Polonia
  • 2,604
  • 3
  • 23
  • 31