2017-08-23 1 views
1

vba(最後の2行目)のcountif関数に問題があります。それは特定の範囲で特定の値を計算しなければなりませんが、絶対にすべての値をmp3としてカウントし、mp4としては何もカウントしません。VBA CountIf issue

変数を渡さずにプロシージャを新しいモジュールにコピーすると、すべて正常に動作し、適切な値が返されます。ここで何が間違っていますか?おかげ

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) 

答えて

4

変更し、これにコードの末尾:

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 
でWtihout

.CellsRangeはactivesheetを参照してください。したがって、自分で参照することをお勧めします。

次に、あなたはそれのように感じる場合は、次のようにコードをリファクタリング:

+0

おかげで、マクロ自体は正常に動作し、問題はmp3とのMP4計算とステップに表示されます。それは適切な範囲を計算します.350のセルは250、4のセルは500ですが、3のcountifは私の結果750を返し、count4のnrは0の値を返します。何が間違っていますか?コードを更新しても、それでも適切にカウントされません。( – muahahahh

+0

@muahahahh - '.'と' With'を加えて変更しましたか? – Vityata