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

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

在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 

通过长度我的意思是非空单元格的数量…为我的具体目的将不会有空白单元格列中,我希望计算列中的所有单元格将包含文本(其余的将是空的) 。

帮助将非常赞赏这个看似简单的事情!

编辑:我也想使这个依赖列索引(这将是'我'在上面的循环)。 我不会一直知道专栏文章

这将计算VBA中的文本非空单元格:

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

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

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

我想你可以使用

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

在列A中查找最后使用的行
浏览每一列,你可以有你想要的…

您可以使用Range(大行号,列)find最后一个非空行。结束(xlUP)。行,其中大行数应该足够大,总是超出您最后使用的单元格。

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

testing数据:

 Col1 Col2 Col3 AAA BB CCC DDD EE 

VBAfunction:

 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 
 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 
 dim i as integer For i = 1 To Columns.Count debug.print i, cells(i, rows.count).end(xlup).row Next