通过工作簿中的Excel工作表循环

时间:2020-06-10 22:56:15

标签: excel vba

我每天导入我的母版,然后在母版的底部计算总数。我在下面计算平均值。然后,我在A和B列的底部执行其他两个平均计算。然后根据市场拆分表,然后程序为每个市场打开一个新标签。然后,我设法拆分了表格,以使数据进入正确的选项卡。我现在想在每个市场上执行相同的总数和平均值计算。市场是一个动态价值-如果在8个市场上有销售,则该程序可能会打开8;如果...等,则该程序可能会打开5。此代码执行求和和平均行计算,但不执行A和B列底部的其他平均计算。我无法执行该操作。

更新...。我已经解决了这一部分问题-我还没有意识到没有sheet.count函数

另外,由于工作簿中的工作表数是动态的,因此我想执行从工作表3到工作簿末尾的计算,我将n用作变量,并且将n设为3到10语句,但是必须有一种方法可以将工作簿中的工作表数量分配给n?

Sub CalcOnSheets()

Application.ScreenUpdating = False
Dim row As Integer
Dim lastRow As Long
Dim ActiveWorksheet As Long
Dim ThisWorksheet As Long
Dim n As Integer



'I've put 3 to 10 here because I don't know how to count the actual number of sheets that I want to 
'run this for Is there a variable which is the count of the sheets in the workbook, as this value is 
'dynamic?

For n = 3 To 10
lastRow = Sheets(n).Cells(Rows.Count, "D").End(xlUp).row
If lastRow > 1 Then
For row = 2 To lastRow

'I've got row 4 in here so the calculations stop performing
'when the iteration gets down to the blank row under the sheet
'but I'm not sure if it's necessary. Could maybe take out the if and the end if

If Sheets(n).Cells(row, 4).Value <> "" Then

Sheets(n).Cells(row, 16).Value = Sheets(n).Cells(row, 10).Value - Sheets(n).Cells(row, 11).Value - _
Sheets(n).Cells(row, 12).Value - Sheets(n).Cells(row, 13).Value - Sheets(n).Cells(row, 14).Value - _
Sheets(n).Cells(row, 15).Value
Sheets(n).Cells(row, 17).Value = Sheets(n).Cells(row, 16).Value / Sheets(n).Cells(row, 10).Value

End If


Next

Dim r As range, j As Long, k As Long
j = Sheets(n).range("A1").End(xlToRight).Column



'This adds up the totals on the sheet
'changing the first value of k stops it adding up un-needed columns
 For k = 9 To j
 Set r = Sheets(n).range(Sheets(n).Cells(1, k), Sheets(n).Cells(1, k).End(xlDown))
 r.End(xlDown).Offset(2, 0) = WorksheetFunction.Sum(r)
 r.End(xlDown).Offset(3, 0) = WorksheetFunction.Average(r)
 Next k


'This deletes the total of the profit margins whch is meaningless
Sheets(n).range("Q" & lastRow).Offset(2) = ""


'This changes the format of column I average value back to two decimal places
 Sheets(n).range("I" & lastRow).Offset(3).NumberFormat = "0.00_);(0.00)"


'These don't work....
'This calculates Average profit per unit
'Sheets(n).range("B" & lastRow).Offset(2, 0).Value = Sheets(n).range("P" & lastRow).Offset(2).Value / Sheets(n).range("I" 
& lastRow).Offset(2).Value
'This calculates Average profit per order
'Sheets(n).range("A" & lastRow).Offset(2, 0).Value = Sheets(n).range("P" & lastRow).Offset(2).Value / Sheets(n).range("D2").End(xlDown).row



Else

MsgBox ("There is no data at column D")
End If

Application.ScreenUpdating = True


Next n

End Sub

我对VBA缺乏经验,只是找到了解决之道。我还想知道是否有一种简单的方法来加宽一些列,以便适合我(第10至17列)

1 个答案:

答案 0 :(得分:0)

我发现了sheet.count函数,该函数可以帮助我解决我正在努力处理的工作表的动态数量:

Dim x As Integer
x = Sheets.Count
For n = 3 To x
next x

我还发现我在这一行中有一个错误:

range("I" & lastRow).Offset(2).Value

应该是哪个:

Sheets(n).range("I" & lastRow).Offset(2).Value
相关问题