Home » excel » excel – If else that checks 2 variables, but won't ignore text

excel – If else that checks 2 variables, but won't ignore text

Posted by: admin May 14, 2020 Leave a comment

Questions:

I am running through a for loop and have an if/else statement that checks the value of the current range and sees if it is larger or equal to 1. The problem is that the value of the current range, can also be text instead of a number.

As I have it now, it sees the text as larger or equal to 1, but how can I add an extra condition to see if it is text or a number?

LastRow = ws1.Cells(Rows.Count, "A").End(xlUp).Row

For i = 3 To LastRow
    If Range("A" & i).Value >= 1 Then
        ws2.Range("A" & var1).Value = ws1.Range("A" & i).Value
        var1 = var1 + 1
    End If
Next i
How to&Answers:

Since VBA will implicitly convert a text string that contains only numbers to a number for this comparison (i.e. 2>"1" is True, and 2>"3" is False), what you actually want to check if the value IsNumeric

If Range("A" & i).Value >= 1 And IsNumeric(Range("A" & i).Value) Then

As GSerg points out below, this will also capture Scientific or Programmer Notations, such as “&hFF” (“&h” means Hexadecimal, and Hexadecimal FF converts into Decimal as 255) or “1d2” / “1e2” (the decimal exponent of 1 by power 2, or 1 * 10^2 = 100). If this is an issue, you may want to consider using RegEx instead.

Answer:

Correction of your Macro

Option Explicit
Sub compaire_with_1()
Dim ws1 As Worksheet, ws2 As Worksheet
Dim LastRow%, i%, var1%: var1 = 1
Set ws1 = Sheets("sheet1"): Set ws2 = Sheets("sheet2")
LastRow = ws1.Cells(Rows.Count, "A").End(xlUp).Row

For i = 3 To LastRow
    If Val(ws1.Range("A" & i)) >= 1 Then
        ws2.Range("A" & var1).Value = ws1.Range("A" & i).Value
        var1 = var1 + 1
    End If
Next i
End Sub

Answer:

May be this macro can works better

    Option Explicit
Sub compaire_with_Digit()
Dim ws1 As Worksheet, ws2 As Worksheet
Dim LastRow%, i%, var1%: var1 = 1
Set ws1 = Sheets("Sheet1"): Set ws2 = Sheets("Sheet2")
LastRow = ws1.Cells(Rows.Count, "A").End(xlUp).Row
ws2.Range("A1").CurrentRegion.ClearContents
For i = 3 To LastRow
   If ws1.Range("A" & i) Like "[1-9]*" Then
        ws2.Range("A" & var1).Value = _
        ws1.Range("A" & i).Value
        var1 = var1 + 1
    End If
Next i
End Sub