I have written a small program to scan through a spreadsheet and calculate the total number of different item types based on a value in a column, then to print the results to specific column locations. My code is below
Sub How_Many_items()
'define variables. A, B, C refer to letter coding. O is other. counter is for the count
Dim A As Integer
Dim B As Integer
Dim C As Integer
Dim O As Integer
Dim Sum As Integer
Dim Counter As Integer
'resetting variables
A = 0
B = 0
C = 0
O = 0
Sum = 0
Counter = 2
'do while loop to continue going down rows until out of new data
'if loops to accumulate values
Worksheets("Values").Select
Do While Worksheets("Values").Cells(Counter, 54) <> Empty
If Worksheets("Values").Cells(Counter, 54).Value = "A" Then
A = A + 1 And Sum = Sum + 1 And Counter = Counter + 1
ElseIf Worksheets("Values").Cells(Counter, 54).Value = "B" Then
B = B + 1 And Sum = Sum + 1 And Counter = Counter + 1
ElseIf Worksheets("Values").Cells(Counter, 54).Value = "C" Then
C = C + 1 And Sum = Sum + 1 And Counter = Counter + 1
ElseIf Worksheets("Values").Cells(Counter, 54).Value <> "A" Or "B" Or "C" Then
Sum = Sum + 1 And Counter = Counter + 1
End If
Loop
'print values in PivotTables worksheet
Worksheets(PivotTables).Cells(I, 20) = Sum
Worksheets(PivotTables).Cells(I, 21) = A
Worksheets(PivotTables).Cells(I, 22) = B
Worksheets(PivotTables).Cells(I, 23) = C
End Sub
Based on looking at other information on this site, I don't actually need the worksheets().select action, but I don't think that is stalling the program.
When stepping through my program it stalls on the loop; the current data in use has "B" in the first column of interest, but it doesnt ever increment to the next row, which makes me think it isn't actually adding to the count or to B for some reason. The column that I am scanning is also a calculated column using a VLOOKUP, but I don't know if that affects what I am doing. The excel worksheet will crash if I try to run the program. Thanks for any help!
C = C + 1 And Sum = Sum + 1 And Counter = Counter + 1is not how it's done... remove theAnd's and put each one on its own line.Worksheets("Values").Cells(Counter, 54).Value <> "A" Or "B" Or "C"doesn't do what you think it does.Application.CountIfto get the counts of A, B, C.