[英]counter loop in Excel
So I've got an Excel workbook with multiple worksheets. 所以我有一个包含多个工作表的Excel工作簿。 Each worksheet is the same template.
每个工作表都是相同的模板。 And cells B3 - B39, C3 - C39, and D3 - D39 will contain 1 of 3 values.
并且单元格B3-B39,C3-C39和D3-D39将包含3个值之一。 1, .5, or no value at all (completely blank).
1,.5或完全没有值(完全空白)。 Now each worksheet isn't exactly the same (some will go to B/C/D45 instead of just B/C/D39).
现在,每个工作表都不完全相同(有些工作表将转到B / C / D45,而不仅仅是B / C / D39)。 I'm trying to have another cell show how many of those cells contain a 1, and another cell show how many contain a .5.
我正在尝试让另一个单元格显示其中有多少个单元格包含1,另一个单元格显示有多少个单元格包含.5。 Yeah I could manually do it, but I'm trying to get this as automated as possible.
是的,我可以手动执行此操作,但是我正在尝试使其尽可能自动化。
As @Variatus has suggested, you could just use the COUNTIF worksheet function, but if you wanted to do this with VBA, what you need to do is: 正如@Variatus所建议的那样,您可以只使用COUNTIF工作表功能,但是如果您想通过VBA进行此操作,则需要执行以下操作:
1
1
.5
.5
Sub CountTheSheets()
Const Value10 As Double = 1, Value05 As Double = 0.5 ' these are what we're comparing cell values against
Dim Count10 As Long, Count05 As Long ' these are our 1 and .5 counts respectively
Dim lastRow As Long, lastRowTemp As Long, maxRow As Long
Dim ws As Worksheet
Dim cel As Range
For Each ws In ThisWorkbook.Worksheets ' iterate over all worksheets
lastRow = 0 ' reset the last row for this worksheet
Count10 = 0 ' reset the 1 count for this worksheet
Count05 = 0 ' reset the .5 count for this worksheet
With ws
maxRow = .Rows.Count ' this is the absolute bottom row in a worksheet
' get last row of column B, by going to the bottom of the worksheet in that column, then using End and going up to find the last cell
lastRowTemp = .Cells(maxRow, "B").End(xlUp).Row
If lastRowTemp > lastRow Then lastRow = lastRowTemp
' get last row of column C; if larger than the previous, store in lastRow that row number instead
lastRowTemp = .Cells(maxRow, "C").End(xlUp).Row
If lastRowTemp > lastRow Then lastRow = lastRowTemp
' get last row of column D; if larger than the previous, store in lastRow that row number instead
lastRowTemp = .Cells(maxRow, "D").End(xlUp).Row
If lastRowTemp > lastRow Then lastRow = lastRowTemp
' build the range using lastRow, and iterate through the cells in that range, counting the matching values
For Each cel In .Range("B3:D" & lastRow)
If cel.Value = Value10 Then
Count10 = Count10 + 1
ElseIf cel.Value = Value05 Then
Count05 = Count05 + 1
End If
Next cel
' do something with these counts
Debug.Print .Name, Count10, Count05
End With
Next ws
End Sub
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.