Search code examples
excelvbaif-statementtype-mismatchmultiple-conditions

How can I compare the data in a cell to see if it is an error, "0" as text, or any other value?


I am trying to write an If statement in VBA for excel to look at the value of a cell and determine if it is "0" (cell is formatted as text), if it's an error, or if it's anything besides those two.

If it is anything besides "0" or an error I want to copy the selection and paste it in another column.

Here is my code snippet:

'Nested For Loop to Extract Values into Column G
        For DCRNumOfParts = LastCellInColumn - 4 To 1 Step -1

            Set SortCell = Cells(SortRow, 5)
            SortCell.Select
            IsCellError = IsError(Selection.Value)

                'If Statement to determine if the cell value is 0 or error state
                'If Selection.Value <> 0 Or VarType(ActiveCell.Value) <> vbError Then
                If Selection.Value <> "0" And IsCellError <> True Then

                    Selection.Copy
                    Set CopyCell = Cells(SortRow, 7)
                    CopyCell.Select
                    ActiveSheet.Paste

                End If

            SortRow = SortRow + 1

        Next DCRNumOfParts

Solution

  • Managed to solve this one myself, I handled the type-mismatch error by doing the following:

    CellAsString = CStr(Selection.Value)
    
    
                    'If Statement to determine if the cell value is 0 or error state
                    'If Selection.Value <> 0 Or VarType(ActiveCell.Value) <> vbError Then
                    If Not IsError(Selection.Value) And CellAsString <> "0" Then