我正在尝试计算我需要用vba查找的两个单元格之间的单元格数。第一个单元格将与当前日期位于同一列中。列标题按日期顺序从左到右(5月1日,5月2日,5月3日等)。一旦我找到了要开始的列,我需要计算向后包含0的单元格数,直到找到没有0的单元格。所以说我从列U开始,我需要计算连续单元格的数量0直到列R为1.然后我的答案是2,因为列T和S有0。
我遇到以下代码的问题是我试图首先根据日期找到我应该在的列(这部分有效)。接下来我将rowNum声明为activecell行号(这部分工作)。接下来我需要找到向后计数的列(此部分不起作用)。我在colNum FIND代码上得到相同的列号,因为我是colStart FIND代码。
我没有收到任何错误,它似乎没有找到前一个单元格为0,而只是给了我相同的列。我希望这很清楚。如果您需要任何其他信息,请与我们联系。谢谢大家!
today = Date
colNum = Cells.Find(today, searchorder:=xlByRows,
searchdirection:=xlPrevious).Column
rowNum = ActiveCell.Row
colStart = Cells.Find(0, after:=Cells(rowNum, colNum),
searchorder:=xlByColumns, searchdirection:=xlPrevious).Column
答案 0 :(得分:0)
尝试以下代码:
Public Function countZeros(ws As Worksheet, rowNum As Long, colNum As Long, Optional stopColumn As Long = 1) As Long
Dim currentCol As Long
countZeros = 0
If colNum <= stopColumn Then Exit Function 'prevents going past a certain point (for example your label column)
For currentCol = colNum - 1 To stopColumn + 1 Step -1
If ws.Cells(rowNum, currentCol) = 0 Then
countZeros = countZeros + 1
Else
Exit Function
End If
Next 'currentCol
End Function
Public Sub mySub()
Dim colNum As Long
Dim rowNum As Long
Dim output As String
Dim today
Dim rng As Range
today = Date
Set rng = Cells.Find(today, searchorder:=xlByRows, searchdirection:=xlPrevious)
If rng Is Nothing Then
MsgBox "Did not find todays date, make sure your active cell is in the right location"
Exit Sub
End If
colNum = rng.Column
rowNum = ActiveCell.Row
output = "Total number of cells from " & Cells(rowNum, colNum).Address & " that have zeros: "
output = output & CStr(countZeros(ActiveWorkbook.ActiveSheet, rowNum, colNum))
MsgBox output
End Sub
使用此数据集:
您将获得输出:
Total number of cells from $K$7 that have zeros: 6