给定列索引的Excel 2010 VBA列长度

时间:2011-10-25 08:03:20

标签: excel vba

鉴于其简单的描述,我发现很难找到答案。我希望这不是重复,虽然可能是因为它简单,我根本找不到答案。

在VBA中,我有数百列,我想知道它们的全部内容。我知道确实有“COLS”专栏。我想要这样的东西:

For i in COLS
   length = 'Some one line formula to find the length of column i
   'Some code that works with the value of length
Next i

按长度我的意思是非空单元格的数量......对于我的特定目的,列中没有空白单元格,我想要计算的列中的所有单元格都将包含文本(其余所有单元格将包含文本)是空的。

在这个看似简单的问题上,我们将非常感谢帮助!

编辑:我也想让它依赖于列索引(在上面的循环中将是'i')。我不会总是知道专栏信......

7 个答案:

答案 0 :(得分:9)

这将在VBA中计算 text 非空单元格:

For i = 1 To Columns.Count
    n = WorksheetFunction.CountA(Columns(i))
Next

答案 1 :(得分:4)

最好使用从所有Excel版本的最后一行自动运行的例程。

Dim lngRow As Long
lngRow = Cells(Rows.Count, "A").End(xlUp).Row

答案 2 :(得分:1)

我认为你可以使用

LastRowColA = Range("A" & Rows.Count).End(xlUp).Row

查找A列中最后使用的行。
浏览每一列你可以得到你想要的......

答案 3 :(得分:0)

您可以使用Range(大行号,列).End(xlUP).row找到最后一个非空行。其中大行号应足够大,以便始终超出上次使用的单元格。

答案 4 :(得分:0)

您可以使用工作表函数CountA使用替代方法,如下所示

测试数据:

Col1 Col2 Col3
A    A    A
     B    B
C    C    C
D    D    D
E         E

VBA功能:

Sub Test()

    Dim sht As Excel.Worksheet
    Set sht = Worksheets("Sheet1")

    Dim i As Integer
    Dim max As Integer
    Dim length As Integer
    max = 0
    For i = 1 To 3
        'CountA returns the number of non-blank cells in a range
        length = WorksheetFunction.CountA(sht.Columns(i))
        If length > max Then max = length
    Next i

MsgBox max - 1 ('remove 1 if you have column headers)

End Sub

答案 5 :(得分:0)

len = sheet1.Range("B" & Rows.Count).End(xlUp).Row ' gives the count of B column
len = sheet1.Range("A" & Rows.Count).End(xlUp).Row ' gives the count of A column

答案 6 :(得分:0)

dim i as integer
For i = 1 To Columns.Count
    debug.print i, cells(i, rows.count).end(xlup).row
Next