2
Sub test()

Dim score As Integer, result As String
score = Range("A1").Value
If score > 0 Then result = "pass"

 Range("b1").Value = result

End Sub

I'm missing something here. In cell A1 i have 0.04 which is > 0 But in B1 I'm not returning pass

Mayukh Bhattacharya
  • 12,541
  • 5
  • 21
  • 32
will6809
  • 21
  • 2
  • 2
    Step through the code (F8 in VBA editor). Where does it go wrong? – RichardCook Jun 08 '23 at 00:37
  • 3
    In math, whole numbers are also called integers. In VBA, the `Integer` data type is used to store whole numbers between ‑32768 and 32768. The preferred data type is `Long` though since it covers more whole numbers. If you need to store decimal numbers, then you need to use the `Double` type: `Dim score As Double`. BTW, 0.04 is automatically converted to a zero if you use the `Integer` data type hence the 'surprising' behavior. Check out the [Docs' data type summary](https://learn.microsoft.com/en-us/office/vba/language/reference/user-interface-help/data-type-summary). – VBasic2008 Jun 08 '23 at 01:23
  • 3
    @VBasic2008: You should write the answer. – JSmart523 Jun 08 '23 at 02:59

3 Answers3

1

If you are new to VBA, it may be better to reference cells and their .Value property, which is a Variant, and is designed to handle values of multiple types more intuitively:

Sub test()
    Dim score As Range: Set score = Range("A1")
    Dim result As Range: Set result = Range("B1")
    If 0 < score.Value Then
        result.Value = "pass"
'    Else
'        result.Value = "fail"
    End If
End Sub
z32a7ul
  • 3,695
  • 3
  • 21
  • 45
1

Populate Conditionally

  • You have chosen the wrong data type for Score as I mentioned in your comments.
  • You want to use the Long data type for whole numbers (see this legendary post why not Integer) and the Double data type for decimal numbers.
  • For more information on data types, read through the documentation.
Sub PopulateConditionally()
    
    Dim ws As Worksheet: Set ws = ActiveSheet ' improve!
    
    ' Could be anything (number, string, boolean, error) so use a 'Variant' type.
    Dim CellValue As Variant: CellValue = ws.Range("A1").Value
    
    Dim Score As Double, Result As String
    
    If VarType(CellValue) = vbDouble Then ' is a number
        Score = CDbl(CellValue) ' explicit conversion (you're in control)
        'Or:
        'Score = CellValue ' implicit conversion (VBA is in control)
        If Score > 0 Then
            Result = "pass"
        'Else ' <=0; do nothing; 'Result' remains an empty string ("")
        End If
    'Else ' is not a number; do nothing; 'Result' remains an empty string ("")
    End If
    
    ws.Range("B1").Value = Result

End Sub
VBasic2008
  • 44,888
  • 5
  • 17
  • 28
0

For this line "Dim score As Integer" you will have to change data type to variant or double. As its integer 0.04 will be stored as 0 in the variable

Rush
  • 71
  • 6