我正在尝试制作3个总计。 批准,拒绝和等待
工作簿中的每个工作表都在同一列中包含此信息。
我到目前为止所尝试的是下面的各种调整,但它似乎错了,我似乎无法理解我是如何做对的。
Sub test()
Dim WS As Worksheet, rng1 As Range, rng2 As Range, rng3 As Range, T1 As Integer, T2 As Integer, T3 As Integer
Dim Lastrow As Long
On Error Resume Next
Set rng1 = Range(("B1"), Range("B" & Rows.Count).End(xlUp))
Set rng2 = Range(("C1"), Range("C" & Rows.Count).End(xlUp))
Set rng3 = Range(("D1"), Range("D" & Rows.Count).End(xlUp))
T1 = 0
T2 = 0
T3 = 0
For Each WS In ActiveWorkbook.Worksheets
With WS
For Each cell In rng1
If cell.Value = "1" Then T1 = T1 + 1
Next
For Each cell In rng2
If Cells.Value = "1" Then T2 = T2 + 1
Next
For Each cell In rng3
If Cells.Value = "1" Then T3 = T3 + 1
Next
End With
Next
MsgBox "Godkendte: " & T1 & "--- Afviste: " & T2 & "--- Afventer: " & T3
End Sub
答案 0 :(得分:2)
您的问题是您在循环之外定义范围,所以:
您还有Cells.Value
而不是Cell.Value
,我将变量更改为更加清晰!
更正后的代码:
Sub test()
Dim wS As Worksheet
Dim rng1 As Range, rng2 As Range, rng3 As Range
Dim RgCell As Range
Dim T1 As Integer, T2 As Integer, T3 As Integer
Dim LastRow As Long
Dim NumberToCount As Integer
Dim StringToCount As String
NumberToCount = 1
StringToCount = CStr(NumberToCount)
T1 = 0
T2 = 0
T3 = 0
For Each wS In ActiveWorkbook.Worksheets
With wS
Set rng1 = .Range(("B1"), .Range("B" & .Rows.Count).End(xlUp))
Set rng2 = .Range(("C1"), .Range("C" & .Rows.Count).End(xlUp))
Set rng3 = .Range(("D1"), .Range("D" & .Rows.Count).End(xlUp))
End With 'wS
For Each RgCell In rng1
If RgCell.Value = NumberToCount Or RgCell.Value = StringToCount Then T1 = T1 + 1
Next RgCell
For Each RgCell In rng2
If RgCell.Value = NumberToCount Or RgCell.Value = StringToCount Then T2 = T2 + 1
Next RgCell
For Each RgCell In rng3
If RgCell.Value = NumberToCount Or RgCell.Value = StringToCount Then T3 = T3 + 1
Next RgCell
Next wS
MsgBox "Godkendte: " & T1 & "--- Afviste: " & T2 & "--- Afventer: " & T3
End Sub
答案 1 :(得分:2)
您的代码可以简化一些。如果您发现自己在末尾编写带有数字的变量名称,那么最好使用数组
Sub test()
Dim ws As Worksheet
Dim v(1 To 3) As Variant
For Each ws In ActiveWorkbook.Worksheets
With ws
v(1) = v(1) + Application.WorksheetFunction.CountIf(.Range(.Range("B1"), .Range("B" & .Rows.Count).End(xlUp)), 1)
v(2) = v(2) + Application.WorksheetFunction.CountIf(.Range(.Range("C1"), .Range("C" & .Rows.Count).End(xlUp)), 1)
v(3) = v(3) + Application.WorksheetFunction.CountIf(.Range(.Range("D1"), .Range("D" & .Rows.Count).End(xlUp)), 1)
End With
Next
MsgBox "Godkendte: " & v(1) & "--- Afviste: " & v(2) & "--- Afventer: " & v(3)
End Sub