2017-10-07 36 views
0

所以我有一个Excel工作簿与多个工作表。每个工作表都是相同的模板。单元格B3 - B39,C3 - C39和D3 - D39将包含3个值中的1个。 1,.5,或根本没有值(完全空白)。现在每张工作表都不完全一样(有些会转到B/C/D45而不是B/C/D39)。我试图让另一个单元格显示有多少个单元格包含1,另一个单元格显示多少个单元格包含1个.5。是的,我可以手动做到这一点,但我试图尽可能自动化。在Excel中计数器循环

+3

看那COUNTIF工作表函数。 – Variatus

+0

这正是我所需要的。这样一个简单的解决方案...感谢您的帮助。 – Desenski

回答

0

由于@Variatus曾建议,你可以只使用COUNTIF工作表函数,但如果你想用VBA做到这一点,你需要做的是:

方法

  1. 确定最后排
  2. 构建范围
  3. 指望有多少在此范围内的单元格包含1
  4. 指望有多少在此范围内的单元格包含.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