Excel VBA确定列的最后一个非值(IE可能有一个公式,但没有值)行

我有一个列在每个行字段中有一个公式。 该公式从另一个excel spreasheet传播数据。 如果行字段中没有任何内容,则该行保持空白。

我在google上find很多例子来获得列中的最后一行。 然而,他们失败了,因为他们检测到这个公式就是有一些东西在里面。 这就说得通了。 但是,如何获得忽略公式的列中的最后一行,并只尝试检测列字段中的值?

我目前使用两种方法来search一个列中的最后一行,其中两个都失败:

函数lastRowA(rngInput As Range)As Variant
     Dim WorkRange As Range
    昏暗我作为整数,CellCount整数
     Application.Volatile
    设置WorkRange = rngInput.Rows(1).EntireRow
    设置WorkRange =相交(WorkRange.Parent.UsedRange,WorkRange)
     CellCount = WorkRange.Count
    对于i = CellCount为1步-1
        如果不是IsEmpty(WorkRange(i))那么
             lastRowA = WorkRange(i).Value
            退出function
        万一
    接下来我
结束function

函数lastRow(列作为string,可选的plusOne作为布尔值)
    如果(plusOne = False)那么
         Plusone精选=假
    万一

    如果(plusOne = False)那么
         lastRow = Replace(Range(column&“65536”)。End(xlUp).Address,“$”,“”)
    其他
         lastRow = Range(column&“65536”)。End(xlUp).Address
         lastRow =单元格(lastRow)
         'replace(,“$”,“”)
    万一
结束function

如果要查找包含非空值的最后一行(由公式生成或input常量),请尝试此操作

Sub FindLastValue() Dim jLastRow As Long jLastRow = ActiveSheet.Cells.Find(What:="*", LookIn:=xlValues, SearchOrder:=xlByRows, SearchDirection:=xlPrevious).Row End Sub 

我从来没有做过这样的事情,但是对于相当大的领域来说,它似乎能够正确快速地工作。 即使你说这个列是所有的公式,这就是一个混合的值和公式,因此外部循环通过区域后退:

 Function GetLastFormulaBlank(rngInput As Excel.Range) As Excel.Range Dim rngFormulas As Excel.Range Dim rngArea As Excel.Range Dim CellCounter As Long Dim AreaCounter As Long Dim varAreaCells As Variant Dim rngLastFormulaBlank As Excel.Range Set rngFormulas = rngInput.SpecialCells(xlCellTypeFormulas) For AreaCounter = rngFormulas.Areas.Count To 1 Step -1 Set rngArea = rngFormulas.Areas(AreaCounter) varAreaCells = rngArea.Value2 If IsArray(varAreaCells) Then For CellCounter = UBound(varAreaCells) To LBound(varAreaCells) Step -1 If varAreaCells(CellCounter, 1) = "" Then Set rngLastFormulaBlank = rngArea.Cells(CellCounter) Exit For End If Next CellCounter Else If varAreaCells = "" Then Set rngLastFormulaBlank = rngArea.Cells(1) End If End If If Not rngLastFormulaBlank Is Nothing Then Exit For End If Next AreaCounter Set GetLastFormulaBlank = rngLastFormulaBlank End Function 

你会这样称呼它:

 Sub test() Dim rngLastFormulaBlank As Excel.Range Set rngLastFormulaBlank = GetLastFormulaBlank(ActiveSheet.Range("A:A")) If Not rngLastFormulaBlank Is Nothing Then MsgBox rngLastFormulaBlank.Address Else MsgBox "no formulas with blanks in range" End If End Sub 

下面是一个简单的方法来find不包含公式的列中的最后一个单元格。 如果没有没有公式的单元格,它将是0。

 Sub Test() Dim i As Long, tempLast As Long, lastRow As Long tempLast = Range("A" & Rows.Count).End(xlUp).Row For i = tempLast To 1 Step -1 If Len(Cells(i, 1)) <> 0 Then If Not Cells(i, 1).HasFormula Then lastRow = i Exit For End If End If Next MsgBox lastRow End Sub 

请注意,您应该使用“rows.count”而不是65536,因为它不再是新版本的Excel中的最后一行。 Rows.count工作,无论版本,或用户设置。 也应该避免使用的范围,因为有一个奇怪的错误,你需要刷新使用的范围,否则你会得到错误的结果。