我前幾天問關於同一工作簿中的問題,它在這裏:Excel countif vba code with criteria resulting with valuesExcel VBA中的計數搜索結果
所以......我得到了下面的代碼。基本上它會搜索給定範圍內的值並檢查另一個單元格中的某個值 - 然後「計數」。至少它應該計數,但它只是輸入1到單元格中。
它工作的很好,但是有可能在給定範圍內有多個搜索結果。我嘗試使用.findnext
,但沒有按照我的意願工作。我也嘗試添加另一個.find
,但仍然是失敗。
如何應對呢?
Sub Wstaw_Szkolenia()
Dim MyRange As Range, MyCell As Variant
Range("A1").Select
liczba = 6
Set MyRange = Range(Selection, Selection.End(xlDown)).Rows.SpecialCells(xlCellTypeVisible)
'PP 2dni 2007
For Each MyCell In MyRange.Cells
With Range("pp2dni2007")
If .Cells.Find(MyCell.Value) Is Nothing Then
Else
If .Cells.Find(MyCell.Value).Offset(0, 3).Value = "TAK" Then
MyCell.Offset(0, liczba).Value = 1
Else
MyCell.Offset(0, liczba).Value = 0
End If
End If
End With
Next
(...)same code, different range(...)
End Sub
修改後的代碼,我看不出有任何遺漏with
標籤。
Sub Wstaw_Szkolenia()
Dim MyRange As Range
Dim rng1 As Range
Dim MyCell As Variant
Dim strAddress As String
liczba = 6
Set MyRange = Range([a1], [a1].End(xlDown)).Rows.SpecialCells(xlCellTypeVisible)
'PP 2dni 2007
For Each MyCell In MyRange.Cells
With Range("pp2dni2007")
Set rng1 = .Cells.Find(MyCell.Value)
If Not rng1 Is Nothing Then
strAddress = rng1.Address
Do
If .Cells.Find(MyCell.Value).Offset(0, 3).Value = "TAK" Then
MyCell.Offset(0, liczba).Value = MyCell.Offset(0, liczba).Value + 1
Else
MyCell.Offset(0, liczba).Value = 0
End If
Set rng1 = .Cells.FindNext(rng1)
Loop While rng1.Address <> strAddress
End If
End With
Next
'PP 3dni 2008
For Each MyCell In MyRange.Cells
With Range("pp3dni2008")
Set rng1 = .Cells.Find(MyCell.Value)
If Not rng1 Is Nothing Then
strAddress = rng1.Address
Do
If .Cells.Find(MyCell.Value).Offset(0, 3).Value = "TAK" Then
MyCell.Offset(0, liczba + 1).Value = MyCell.Offset(0, liczba + 1).Value + 1
Else
MyCell.Offset(0, liczba + 1).Value = 0
End If
Set rng1 = .Cells.FindNext(rng1)
Loop While rng1.Address <> strAddress
End With
Next
(...and repeats for different ranges...)
End Sub
嗯,不知何故,我不明白這個問題。你可以嘗試重新措辭,並使我的目的更清楚嗎? – Trace