Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
195 views
in Technique[技术] by (71.8m points)

VBA function returns correctly a value the first time, but not the second time it runs

So when I run this I just get the number of rows in total instead of a count of the empty rows only. It worked once, but then it keeps giving me back the total from B4 until LastRowNumber. Can't figure out why..

Function CheckBlankCells(worksheetName As String)
  nrows = 0
  Set ws = ThisWorkbook.Worksheets(worksheetName)
  LastRowNumber = ws.Cells(Cells.Rows.Count, "B").End(xlUp).Row
  
  For Each cell In ws.Range("B4:B" & LastRowNumber)
    If Not IsEmpty(cell) Then
      If Range("C" & cell.Row) = "" Or IsEmpty(Range("C" & cell.Row)) Then
          nrows = nrows + 1
      End If
    End If
  Next
  CheckBlankCells = nrows
End Function

I also tried to do:

If Not IsEmpty(cell) And IsEmpty(Range("C" & cell.Row))

But with the same result.

question from:https://stackoverflow.com/questions/65901610/vba-function-returns-correctly-a-value-the-first-time-but-not-the-second-time-i

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

As SJR suggested, I missed ws before the Ranges. So I had to change this bit:

If Range("C" & cell.Row) = "" Or IsEmpty(Range("C" & cell.Row)) Then

to this on line 8 of the function:

If ws.Range("C" & cell.Row) = "" Or IsEmpty(ws.Range("C" & cell.Row)) Then

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...