【发布时间】:2020-02-27 14:50:17
【问题描述】:
我编写了一个小程序来扫描电子表格并根据列中的值计算不同项目类型的总数,然后将结果打印到特定的列位置。我的代码如下
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
根据查看此站点上的其他信息,我实际上并不需要 worksheets().select 操作,但我认为这不会导致程序停滞。
当单步执行我的程序时,它会在循环中停止;当前使用的数据在感兴趣的第一列中有“B”,但它永远不会增加到下一行,这让我认为它实际上并没有添加到计数或出于某种原因添加到 B。我正在扫描的列也是使用 VLOOKUP 计算的列,但我不知道这是否会影响我正在做的事情。如果我尝试运行该程序,excel 工作表将崩溃。感谢您的帮助!
【问题讨论】:
-
C = C + 1 And Sum = Sum + 1 And Counter = Counter + 1不是这样的...删除And并将每个放在自己的行中。 -
Worksheets("Values").Cells(Counter, 54).Value <> "A" Or "B" Or "C"并没有按照你的想法去做。 -
这里不需要循环 - 只需使用
Application.CountIf来获取 A、B、C 的计数。