循环通过活动工作簿中的工作表无法正常工作

时间:2016-09-08 21:26:30

标签: excel vba excel-vba

我正在使用多个工作表(动态),并希望在每个工作表(VBA初学者)上进行一些简单的计算。我可以在每张纸上做宏 单独但循环不起作用。没有错误消息,但只在一张纸上执行。代码如下。任何帮助表示赞赏。

Sub Counts()

Dim Last As Integer
Dim Have As Long
Dim Miss As Long
Dim Total As Long
Dim Value As Currency
Dim Cost As Currency
Dim TVal As Currency
Dim ws As Worksheet



For Each ws In ActiveWorkbook.Worksheets

Last = Range("B1").CurrentRegion.Rows.Count

Miss = Application.WorksheetFunction.CountBlank(Range("A2:A" & Last))
Total = Last - 1
Have = Total - Miss

Value = Application.WorksheetFunction.SumIf(Range("A2:A" & Last), "X",Range   ("G2:G" & Last))
TVal = Application.WorksheetFunction.Sum(Range("G2:G" & Last))
Cost = TVal - Value

Range("J2").Value = "Have"
Range("J3").Value = "Missed"
Range("J4").Value = "Total Cards"
Range("J6").Value = "Value"
Range("J7").Value = "Cost to Complete"
Range("J8").Value = "Set Value"

Range("k2").Value = Have
Range("k3").Value = Miss
Range("k4").Value = Total
Range("k6").Value = Value
Range("k7").Value = Cost
Range("k8").Value = TVal

Next ws

End Sub

1 个答案:

答案 0 :(得分:2)

默认情况下,Range指的是活动工作表,循环工作表并不意味着每个工作表都会自动激活。您应该始终尝试准确指定您所指的是哪个工作表。无论您使用ws.Range,以下代码均使用Range。 (并使用With ws块,以便ws.Range可以简化为.Range。)

Sub Counts()

Dim Last As Integer
Dim Have As Long
Dim Miss As Long
Dim Total As Long
Dim Value As Currency
Dim Cost As Currency
Dim TVal As Currency
Dim ws As Worksheet



For Each ws In ActiveWorkbook.Worksheets

    With ws
        'I modified the next line to not use "CurrentRegion" as I wasn't
        'sure whether "CurrentRegion" would be meaningful without first
        'selecting a cell.
        Last = .Range("B" & .Rows.Count).End(xlUp).Row

        Miss = Application.WorksheetFunction.CountBlank(.Range("A2:A" & Last))
        Total = Last - 1
        Have = Total - Miss

        Value = Application.WorksheetFunction.SumIf(.Range("A2:A" & Last), "X",.Range("G2:G" & Last))
        TVal = Application.WorksheetFunction.Sum(.Range("G2:G" & Last))
        Cost = TVal - Value

        .Range("J2").Value = "Have"
        .Range("J3").Value = "Missed"
        .Range("J4").Value = "Total Cards"
        .Range("J6").Value = "Value"
        .Range("J7").Value = "Cost to Complete"
        .Range("J8").Value = "Set Value"

        .Range("k2").Value = Have
        .Range("k3").Value = Miss
        .Range("k4").Value = Total
        .Range("k6").Value = Value
        .Range("k7").Value = Cost
        .Range("k8").Value = TVal

    End With    
Next ws

End Sub