Eray Balkanli
Eray Balkanli

Reputation: 7990

Visual basic - my string comparison function not working correctly

I have data like: (id,volume,median.percantile)

1  Normal Normal Low
2  Low Normal High
3  High High Normal

What I need to do is to have a counter that it increases by 1 when it is not Normal. So I expect

1  Normal Normal Low Counter:1
2  Low Normal High Counter:2
3  High High Low Counter:3 

To provide it I wrote the function below. However, when I send there (Normal,Normal,High), it is calculating it 2 instead 1. So it is not working correctly. Where is my mistake?

My code is below:

Public Function getPoint(ByVal volume As String, ByVal median As String, ByVal percantile As String) As Integer

  Dim Total As Integer = 0
  If volume = “Normal” then 
    total = total + 1 
  end if
  If median = “Normal” then 
    total = total + 1
  end if
  If percantile = “Normal” then 
    total = total + 1 
  end if

  return total

End Function

Upvotes: 0

Views: 82

Answers (3)

Mark Miller
Mark Miller

Reputation: 156

Change your "="'s to "<>"
i.e.

If volume <> "Normal" then 
    total = total + 1 
End if

Upvotes: 0

Techie
Techie

Reputation: 1491

What you are doing is opposite to what you want.

You want the count of not-Normal whereas what you are counting and returning the total is Normal.

Simple fix would be return (3 - total).

Btw, is this VBA or VB.Net? Both are based on VB but are different. If it's VBA for Excel, you can achieve this using simple count formula (3 - count of Normal).

Upvotes: 0

David
David

Reputation: 219057

In the first record, both volume and median are "Normal". So both of these conditions are true:

If volume = "Normal" Then 
  total = total + 1 
End If
If median = "Normal" Then 
  total = total + 1
End If

Thus, total gets incremented twice. If you want it to be incremented only once (and essentially ignore the remaining comparisons) then use ElseIf to stop the comparisons once a condition has been satisfied:

If volume = "Normal" Then 
  total = total + 1 
ElseIf median = "Normal" Then 
  total = total + 1
End If

Or just put them into a single condition:

If volume = "Normal" Or median = "Normal" Then
  total = total + 1
End If

Note that this behavior is exactly the opposite of what you describe:

increases by 1 when it is not Normal

A typo perhaps?

Upvotes: 1

Related Questions