vba 如何找到列中的第一个非空白单元格?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6335917/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-08 11:35:10  来源:igfitidea点击:

How do I find the first nonblank cell in a column?

excelvba

提问by Ari

The first row is all headers, and the first column are all dates. I am looking for vba code/macro to find and select the first non empty cell in each column after the headers. For example find the first nonempty cell in the range B2 and select it.

第一行都是标题,第一列都是日期。我正在寻找 vba 代码/宏来查找并选择标题后每列中的第一个非空单元格。例如,找到范围 B2 中的第一个非空单元格并选择它。

回答by Reafidy

IFyour first row is a header row then you can use:

如果您的第一行是标题行,那么您可以使用:

Columns("B").SpecialCells(xlCellTypeBlanks)(1).Select

EDIT

编辑

Sorry misread the question, above code is totally wrong. A solution:

抱歉误读了这个问题,上面的代码是完全错误的。一个办法:

Note: Their is a difference between blank and empty.

注意:它们是空白和空的区别。

For First Non-Blank (as in question title) Try:

对于第一个非空白(如问题标题)尝试:

With Columns("B")
    .Find(what:="*", after:=.Cells(1, 1), LookIn:=xlValues).Activate
End With

For First Non-Empty (as in question body) Try:

对于第一个非空(如问题正文)尝试:

Unlike above this will also find non-empty cells where a formula equates to blank ie =IF(A1=1,A1,"")

与上面不同,这也会找到公式等于空白的非空单元格,即 =IF(A1=1,A1,"")

With Columns("B")
    .Find(what:="*", after:=.Cells(1, 1), LookIn:=xlFormulas).Activate
End With

回答by GSerg

In each column i, the first non empty cell is

在每一列中i,第一个非空单元格是

set first_ne = cells(2,i)

if isempty(first_ne.value) then
  set first_ne = first_ne.end(xldown)
end if

回答by Alex P

Using the IsEmptyfunction can check if a cell is blank or not:

使用该IsEmpty函数可以检查单元格是否为空白:

Sub GetFirstNonEmptyCell()
    Dim startCell as range, firstNonEmptyCell as range

    Set startCell = Range("B2") 'change this depending on which column you are looking at

    If VBA.IsEmpty(startCell.Value) Then
        MsgBox "No data in this column"
    Else
        Set firstNonEmptyCell = startCell.End(xlDown)
        MsgBox "First non empty cell is " & firstNonEmptyCell.Address
    End If    
End Sub