简体   繁体   English

使用VBA查找Excel工作表中的非空白列数

[英]Finding the number of non-blank columns in an Excel sheet using VBA

How do I find the number of used columns in an Excel sheet using VBA? 如何使用VBA在Excel工作表中查找已使用的列数?

Dim lastRow As Long
lastRow = Sheet1.Range("A" & Rows.Count).End(xlUp).Row
MsgBox lastRow

Using the above VBA I'm able to find the number of rows. 使用上面的VBA,我能够找到行数。 But how do I find the number of columns in my given excel file? 但是如何在给定的excel文件中找到列数?

Your example code gets the row number of the last non-blank cell in the current column, and can be rewritten as follows: 您的示例代码获取当前列中最后一个非空单元格的行号,可以按如下方式重写:

Dim lastRow As Long
lastRow = Sheet1.Cells(Rows.Count, 1).End(xlUp).Row
MsgBox lastRow

It is then easy to see that the equivalent code to get the column number of the last non-blank cell in the current row is: 然后很容易看出,获取当前行中最后一个非空单元格的列号的等效代码是:

Dim lastColumn As Long
lastColumn = Sheet1.Cells(1, Columns.Count).End(xlToLeft).Column
MsgBox lastColumn

This may also be of use to you: 这也可能对您有用:

With Sheet1.UsedRange
    MsgBox .Rows.Count & " rows and " & .Columns.Count & " columns"
End With

but be aware that if column A and/or row 1 are blank, then this will not yield the same result as the other examples above. 但请注意,如果列A和/或行1为空,则不会产生与上述其他示例相同的结果。 For more, read up on the UsedRange property. 有关更多信息,请阅读UsedRange属性。

Jean-François Corbett's answer is perfect. Jean-FrançoisCorbett的答案是完美的。 To be exhaustive I would just like to add that with some restrictons you could also use UsedRange.Columns.Count or UsedRange.Rows.Count . 为了详尽无遗,我只想添加一些限制,你也可以使用UsedRange.Columns.CountUsedRange.Rows.Count
The problem is that UsedRange is not always updated when deleting rows/columns (at least until you reopen the workbook). 问题是删除行/列时并不总是更新UsedRange(至少在重新打开工作簿之前)。

It's possible you forgot a sheet1 each time somewhere before the columns.count , or it will count the activesheet columns and not the sheet1 's. 这是可能的,你忘了sheet1的前每次某处columns.count ,否则会算activesheet列,而不是sheet1的。

Also, shouldn't it be xltoleft instead of xltoright? 另外,不应该是xltoleft而不是xltoright? (Ok it is very late here, but I think I know my right from left) I checked it, you must write xltoleft. (好吧,现在已经很晚了,但我想我从左开始知道我的权利)我查了一下,你必须写xltoleft。

lastColumn = Sheet1.Cells(1, sheet1.Columns.Count).End(xlToleft).Column

This is the answer: 这就是答案:

numCols = objSheet.UsedRange.Columns.count

Documentation of the UsedRange property UsedRange属性的文档

Result is shown in the following code as column number (8,9 etc.): 结果显示在以下代码中作为列号 (8,9等):

Dim lastColumn As Long
lastColumn = Sheet1.Cells(1, Columns.Count).End(xlToLeft).Column
MsgBox lastColumn

Result is shown in the following code as letter (H,I etc.): 结果在以下代码中显示为字母 (H,I等):

Dim lastColumn As Long
lastColumn = Sheet1.Cells(1, Columns.Count).End(xlToLeft).Column
MsgBox Split(Sheet1.Cells(1, lastColumn).Address, "$")(1)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM