我正在尝试编写一个看一列的宏,如果一个单元格不为空,则将所有值加在一起,并计算添加了多少个单元格。
问题是该列中的所有单元格都引用另一张纸上的其他单元格。因此,从技术上讲,所有单元格中都有某些内容(例如,=Detail!E5
之类的内容)。
要计数的单元格具有0到100之间的数字。“空白”单元格具有引用原始单元格的公式,并且该公式正在返回
" "
(空格)。
有人知道如何实现吗?
我尝试了几件事,但是它们总是只返回所有单元格的计数,而不是填充的单元格。
Set myRange = Range("J13")
For iCol = 0 To 18
If myRange.Offset(0, iCol).Value > result Then
For iRow = 17 To 31
If myRange.Offset(iRow, iCol).Value <> " " Then
counter = counter + 1
Debug.Print (counter)
End If
Next iRow
End If
Next iCol
答案 0 :(得分:2)
SpecialCells可以确定公式是否返回了文本或数字,但是使用简单的工作表功能可能会更好。
dim n as long, t as long
Set myRange = Range("J13")
For iCol = 0 To 18
If myRange.Offset(0, iCol).Value > result Then
with myRange.Offset(17, iCol).resize(15, 1)
'count numbers returned from formulas
n = application.count(.cells)
'count text returned from formulas
t = application.counta(.cells) - application.count(.cells)
debug.print n & "numbers"
debug.print t & "texts"
on error resume next
'count numbers returned from formulas
n = 0
n = .specialcells(xlCellTypeFormulas, xlNumbers).count
'count text returned from formulas
t = 0
t = .specialcells(xlCellTypeFormulas, xlTextValues).count
on error goto 0
debug.print n & "numbers"
debug.print t & "texts"
end with
End If
Next iCol
答案 1 :(得分:0)
目前尚不清楚result
是什么。调整常量部分。
Sub CountVals()
Const cSheet As String = "Sheet1"
Const cRange As String = "J13"
Const cCols As Long = 19
Const cFirstR As Long = 30
Const cLastR As Long = 44
Const result As Long = 21 ' Long, Single, Double ?
Dim myRange As Range
Dim FirstC As Long
Dim LastC As Long
Dim counter As Long
Dim colCounter As Long
Dim summer As Long
Dim colSummer As Long
Dim i As Long
Dim j As Long
With ThisWorkbook.Worksheets(cSheet)
Set myRange = .Range(cRange)
FirstC = myRange.Column
LastC = FirstC + cCols - 1
For j = FirstC To LastC
Set myRange = .Cells(myRange.Row, j)
If myRange.Value > result Then
For i = cFirstR To cLastR
If IsNumeric(.Cells(i, j).Value) Then
summer = summer + .Cells(i, j).Value
colSummer = colSummer + .Cells(i, j).Value
counter = counter + 1
colCounter = colCounter + 1
End If
Next
Debug.Print "Column" & j & " = " & colSummer & "(" _
& summer & ") - " & colCounter & "(" _
& counter & ")" ' for each column
colCounter = 0
colSummer = 0
End If
Next
End With
End Sub