行计算excel 2007 VBA中的问题

时间:2014-08-26 16:29:23

标签: excel vba excel-vba

我的这个宏一直工作得很完美,但最近它错过了3次计数,但仍然可以正常工作3次。我使用Countif来计算excel的内容,仍然错过了一个数字。我看不出有任何不同的相同值,为什么它错过了那个。这是代码。

Dim DP1_total As Integer


 Range("H1").Sort Key1:=Range("H2"), Order1:=xlDescending, Header:=xlYes
 FinalRowH = Range("H1048576").End(xlUp).Row

  DP1_total = 0
  For i = 2 To FinalRowH
    If Range("H" & i).Value = "DP1" Then
      DP1_total = DP1_total + 1
    End If
  Next i

  If DP1_total > 0 Then
    MsgBox (DP1_total)
  End If

1 个答案:

答案 0 :(得分:0)

我没有收到以下代码的错误。我摆脱了你的FinalRowH变量,只需将循环结束设置为等于.end(xlup)。另一个改进是创建一个变量来遍历每个单元格并找到值。

Dim DP1_total As Integer
Dim FinalRowH As Range
Dim i As Integer
Range("H1").Sort Key1:=Range("H2"), Order1:=xlDescending, Header:=xlYes

  DP1_total = 0
  For i = 2 To Range("$H$1048567").End(xlUp).Row
    If ThisWorkbook.Sheets(1).Range("H" & i).Value = "DP1" Then
      DP1_total = DP1_total + 1
    End If
  Next i

  If DP1_total > 0 Then
    MsgBox (DP1_total)
  End If