【问题标题】:VBA CountIf issueVBA CountIf 问题
【发布时间】:2018-02-15 01:48:02
【问题描述】:

vba 中的 countif 函数有问题(最后两行代码)。它必须计算一定范围内的某些值,但是它绝对将每个值都计为 mp3 而没有任何值计为 mp4。

最奇怪的是,当我将程序复制到一个新的单独模块中时,没有传递变量,一切正常,返回正确的值。这里有什么问题?谢谢

Private Sub FindValue(ByVal fileno As String, ByVal deadline As String)

Dim i As Integer
Dim xWs As Worksheet
Dim rng As Range
Dim olApp As Object
Dim olMail As Object
Dim var As Integer
Dim user As String
Dim uplDate As String
Const olMailItem = 0
Dim lastrow As Long
Dim mp3 As Long
Dim mp4 As Long

Sheets("Add_User_ID").Select
var = Sheets("Add_User_ID").Range(("A2"), Sheets("Add_User_ID").Range("A2").End(xlDown)).Rows.Count
If fileno = "" Then
fileno = InputBox("File number")
End If
If deadline = "" Then
deadline = InputBox("Deadline, any format(e.g. 27th of August EOD)")
End If
uplDate = Format(Date, "YYYYMMDD")

For i = 2 To var + 1
user = Sheets("Add_User_ID").Cells(i, "A").Value
Sheets("allocation").Select
With ActiveSheet
    .AutoFilterMode = False
    .Range("A:I").AutoFilter
    .Range("A:A").AutoFilter field:=1, Criteria1:=user
End With

Sheets("allocation").Range("A1").Select
Set rng = ActiveCell.CurrentRegion
Application.Workbooks.Add
Set xWs = Application.ActiveSheet
rng.Copy Destination:=xWs.Range("A1")
lastrow = xWs.Cells(Rows.Count, 2).End(xlUp).Row - 1
mp3 = WorksheetFunction.CountIf(Range(Cells(2, 4), Cells((lastrow + 1), 4)), 3)
mp4 = WorksheetFunction.CountIf(Range(Cells(2, 4), Cells((lastrow + 1), 4)), 4)

【问题讨论】:

    标签: vba excel countif


    【解决方案1】:

    把代码结尾改成这样:

    with xWs
        mp3 = WorksheetFunction.CountIf(.Range(.Cells(2, 4), .Cells((lastrow + 1), 4)), 3)
        mp4 = WorksheetFunction.CountIf(.Range(.Cells(2, 4), .Cells((lastrow + 1), 4)), 4)
    end with
    

    没有 With 和 .CellsRange 指的是活动表。因此,最好自己参考。

    然后,如果您愿意,请像这样重构您的代码:

    【讨论】:

    • 谢谢,宏本身工作正常,问题出现在mp3和mp4计算的步骤上。它计算正确的范围,假设 250 个单元格的值为 3,500 个单元格的值为 4,但是 nr 3 的 countif 返回我的结果 750 和 nr 4 的 countif 返回值 0,这是绝对错误的。即使我根据您的建议更新了代码,它仍然不能正确计算:(
    • @muahahahh - 你改了吗,添加了.With
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-08-25
    • 1970-01-01
    • 2017-06-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多