0

I'm writing a macro and I'm having a hard time understanding excel. The macro check if certain cells are the same, and if the subtraction of cells is less than 103, then it executes code. I'm getting stuck when I try to subtract two cells and assign it to a variable. Any Pointers?

Sub range1()
    Dim numResult As Integer

    For CHARS = 1 To 20000

        If Cells(CHARS, 1) = "" Then CHARS = 20000

        For n = 1 To 50
            If ([CELLS(CHARS, 1)] = [CELLS(CHARS + 1, 1)]) Then
               If ([CELLS(CHARS, 4)] = [CELLS(CHARS + 1, 4)]) Then
                  numResult = Evaluate([CELLS(CHARS + 1, 2)] & "-" & [CELLS(CHARS, 3)]) '//ERROR
                  If (numResult < 103) Then
                     Cells(CHARS + 1, 3).Select
                     Selection.Cut Destination:=Cells(CHARS, 3)
                     Rows("(CHARS + 1):(CHARS + 1)").Select
                     Selection.Delete Shift:=xlUp
                  End If
               End If
            Else
                Exit For
            End If
         Next n

    Next CHARS
End Sub
Community
  • 1
  • 1
user2817749
  • 134
  • 9

1 Answers1

0

There are plenty of ways in which you could improve your code, but the bottom line is that if

 numResult = Evaluate([CELLS(CHARS + 1, 2)] & "-" & [CELLS(CHARS, 3)])

throws the error Type mismatch, then the things you are subtracting cannot be subtracted - or they cannot be assigned to an Integer. Most likely one of the cells contains text, or nothing.

I would recommend changing the line

Dim numResult As Integer

to

Dim numResult

That way, "any result" can be assigned to the variable, and you might be able to figure out what is going on.

EDIT if the End If would make things better, you have a problem understanding the structure of the If statement.

x = 3
If (1 = 1) Then x = 4
   MsgBox "hello"

results in x = 4, and the message "hello". But

x = 3
If (1 = 0) Then x = 4
   MsgBox "goodbye"

results in x = 3, and "goodbye". In other words - indentation alone doesn't cause the If to continue to the next line. For that you would need:

If (1 = 0) Then
  x = 4
  MsgBox "goodbye"
Else
  MsgBox "hello"
End If

So - you create a Block If when you have NOTHING AFTER THE Then - and then you need an End If. Otherwise, it's just the next statement after the Then that gets executed.

Does that help?

A thought: since you set CHARS to 20000 when you reach a blank cell, and you then execute the next code block, you will in fact try to evaluate (probably) - (blank minus blank) which cannot be put in an Integer… but I'm speculating a bit about the contents of your file, I must admit.

Floris
  • 45,857
  • 6
  • 70
  • 122
  • Good point about evaluating a blank cell. Yeah, I had a bit of trouble with End If, I'm a little more accustomed to brackets. – user2817749 Dec 10 '13 at 03:22