循环浏览活动工作簿中的工作表无法正常工作

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

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 

默认情况下,“ Range指的是活动工作表,循环显示工作表并不意味着每个工作表都会自动激活。 您应该始终尝试指定您正在引用的表。 下面的代码在使用ws.Range地方使用ws.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