【问题标题】:Skip empty rows in Excel column跳过 Excel 列中的空行
【发布时间】:2012-06-07 21:51:35
【问题描述】:

在用户在 Excel 中选择一整列并且我必须对列内的单元格进行操作的情况下,我如何有效地忽略空行。一整列有超过 100 万个单元格!请帮忙!

范围来自

var range = Application.ActiveWindow.RangeSelection;

最终我想做一些事情

    for (int i = 0; i < range.Rows.Count; i++)

其中 Rows.Count 应该是非空行数...也许有一种方法可以找到最后一个包含某些内容的单元格?

【问题讨论】:

    标签: excel vsto


    【解决方案1】:

    几个选项取决于您的范围内是否有空格(使用方法 1),或者更简单地说,如果您想找到最后使用的单元格(使用方法 3)

    这些选项以activesheet的A列为例

    1.特殊细胞

    如果空单元格确实是空的,那么您可以使用SpecialCells 处理公式单元格(以= 开头)和/或常量单元格

       Sub GetNonEmtpy()
        Dim rng1 As Range
        Dim rng2 As Range
        On Error Resume Next
        Set rng1 = Columns("A").SpecialCells(xlConstants)
        Set rng2 = Columns("A").SpecialCells(xlFormulas)
        On Error GoTo 0
        If Not rng1 Is Nothing Then MsgBox "Constants in " & rng1.Address(0, 0)
        If Not rng2 Is Nothing Then MsgBox "formula in " & rng2.Address(0, 0)
        'then work with these ranges
    End Sub
    

    2。最后一个单元格查找

    Sub LastCellLookup()
        Dim rng1 As Range
        Set rng1 = Cells(Rows.Count, "A").End(xlUp)
        If rng1.Row <> 1 Then
            MsgBox "last cell is " & rng1.Address(0, 0)
        Else
        'check first cell is not empty
            If Len(rng1.Value) > 0 Then
                MsgBox "last cell is " & rng1.Address(0, 0)
            Else
                MsgBox "row is blank"
            End If
        End If
    End Sub
    

    3.查找

    Sub LastCellFind()
        Dim rng1 As Range
        Set rng1 = Columns("A").Find("*", [a1], xlValues, , xlByRows, xlPrevious)
        If Not rng1 Is Nothing Then MsgBox "Last cell is " & rng1.Address(0, 0)
    End Sub
    

    【讨论】:

    • 这很有帮助。在我的例子中,行之间有空白,看起来#2 只从顶部查看连续的块。我有(行,行,行,空白,行),它报告 3 是最后一行,而不是 5。
    • @tofutim (2) 的代码看起来是自下而上的,所以应该返回第 5 行。你是在右列上运行它吗?我现在看到这是 VSTO 而不是 VBA
    • 应该差不多。在我的测试中,我的第一行是空白的,我认为 End 可能会以某种方式寻找最后一个空白行......
    • 方法 3,顺便说一句,仅适用于未过滤的数据。它不查看过滤后的数据。
    【解决方案2】:

    在我看来,您想知道行数的上限是多少,这样您就不会一直循环到工作簿的底部。

    如果是这种情况,那么您可能正在寻找 Worksheet.UsedRange 属性,该属性包含曾经使用过的所有单元格的范围(包括输入值然后删除的单元格)。

    例如,

    Dim MaxUsedRow As Integer
    MaxUsedRows = ActiveSheet.UsedRange.Row + ActiveSheet.UsedRange.Rows.Count - 1
    MsgBox MaxUsedRows
    

    将显示整个工作簿中最后使用的行的索引。

    【讨论】:

      猜你喜欢
      • 2016-05-03
      • 2020-10-07
      • 1970-01-01
      • 1970-01-01
      • 2018-04-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多