简体   繁体   中英

How to count a variable with two conditions VBA Excel

I'm working on a project about housing on my campus, University of Illinois Urbana-Champaign.

I want to count based on two conditions: if the house is a fraternity (coded as "1") and if it is in Champaign (if the address *61820).

Here is my macro:

Sub ChampFrat()

  Dim Champaign As Integer
  Champaign = 0

  If Range("$B2:$B79").Value = "1" And Range("$C2:$C79").Value = "*61820" Then
    Range("$B$82").Value = (Champaign = Champaign + 1)
  Else
    Range("$B$82").Value = (Champaign = Champaign + 0)
  End If
End Sub

I am getting a "type mismatch" error.

I will need to create five other similar macros; one counting for fraternities ("1") in Urbana (*61801), one for counting sororities ("0") in Champaign (address *61820), one for counting sororities ("0") in Urbana (*61801), one for counting co-ed houses ("2) in Champaign (*61820) and one for counting co-ed houses ("2") in Urbana (*61801).

I learned VBA and MySQL in a class and have not used it much since, but I want to learn it better for projects such as this. I apologize for upvoting or answering other questions yet; I haven't been on StackOverflow for very long. I sincerely appreciate any help.

You can't assign a value in VB on the right side of an equations like your trying here:

Range("$B$82").Value = (Champaign = Champaign + 1)

Change it to this:

Range("$B$82").Value = Champaign + 1

I'm assuming you want to check each value not a whole range of values at once. You'll need to loop through the range and test each one individually.

Sub ChampFrat()

  Dim Champaign As Integer
  Champaign = 0

  Dim rRng As Range
  Set rRng = Range("$B2:$B79")

  For Each cell In rRng.Cells
    If cell.Value = "1" And cell.offset(0,1).Value Like "*61820" Then
      Champaign = Champaign + 1
      Range("$B$82").Value = Champaign
    Else
      Range("$B$82").Value = Champaign
    End If
  Next
End Sub

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM