macro if statement

gerson02

New Member
Joined
Sep 9, 2018
Messages
10
Hello again,

i want to create a macro that will compute the rating. when I run the macro and click the button,
I receive Run-time Error '13': Type Mismatch when I try to run the code. Debug highlights the 'IF' statements, but I can't figure out where the mistake is. Any help would be appreciated. Thanks

Private Sub CommandButton1_Click()
Dim score As Integer, result As String
rating = Range("E6:E20").Value

If rating > "98.5%" Then
result = "Exceeds"
ElseIf rating = "96% > 98.49%" Then
result = "Meets"
Else
result = "Needs"
End If

Range("F6:F20").Value = result
End Sub



SCORERATINGRANGERATING
95.00% must be "Needs"98.50% - 100%Exceeds
98.01% must be "Meets"96% - 98.49%Meets
99.00% must be "Exceeds"below 96%Needs
99.50%
97.66%
94.50%
95.78%
98.56%
97.69%
95.45%
98.00%
99.97%
98.99%
97.97%
98.95%

<tbody>
</tbody>
 

Some videos you may like

Excel Facts

Get help while writing formula
Click the italics "fx" icon to the left of the formula bar to open the Functions Arguments dialog. Help is displayed for each argument.

Rick Rothstein

MrExcel MVP
Joined
Apr 18, 2011
Messages
35,907
Office Version
2010
Platform
Windows
The reason for the error is that you assigned all of the values in range E6:E20 to the rating variable. That assignment created a two-dimensional array of values (yes, two-dimensional even though the values come from a single column). In your "If" statement, you are asking if that array equals a text string... that is your type mismatch. You will need to set up a loop and run through and test each array element and assign those individual results to the result variable (which will need to be an array equal in size to the rating array). Also your "ElseIf" comparison is not correct. Try something like this maybe...
Code:
Private Sub CommandButton1_Click()
  Dim R As Long, Rating As Variant, Result As Variant
  Rating = Range("E6:E20").Value
  ReDim Result(1 To UBound(Rating), 1 To 1)
  For R = 1 To UBound(Rating)
    If Rating(R, 1) >= "98.5%" Then
      Result(R, 1) = "Exceeds"
    ElseIf Rating(R, 1) > "96% and Rating(R,1) < 98.5%" Then
      Result(R, 1) = "Meets"
    Else
      Result(R, 1) = "Needs"
    End If
  Next
  Range("F6:F20").Value = Result
End Sub
Note: I am not totally sure (and cannot know without more information), but I don't think your "If" and "ElseIf" tests will work... it kind of depends on what is in the cells you are testing. If the values are numeric percentages, then their value (what you stored in the Result array) will be smaller numbers without the percent symbol, so you would need to test (for the "If" for example) against 0.985, not "98.5%".
 

gerson02

New Member
Joined
Sep 9, 2018
Messages
10
it works. i used 0.985 instead of "98.5%" thank you so much you're the best.
 

Watch MrExcel Video

Forum statistics

Threads
1,099,045
Messages
5,466,219
Members
406,473
Latest member
Dunno123

This Week's Hot Topics

Top