如何使用VBA查找Excel表单中使用的列的数量?使用VBA查找Excel表单中非空白列的数量
Dim lastRow As Long
lastRow = Sheet1.Range("A" & Rows.Count).End(xlUp).Row
MsgBox lastRow
使用上面的VBA我能够找到行数。但是,如何查找给定的excel文件中的列数?
如何使用VBA查找Excel表单中使用的列的数量?使用VBA查找Excel表单中非空白列的数量
Dim lastRow As Long
lastRow = Sheet1.Range("A" & Rows.Count).End(xlUp).Row
MsgBox lastRow
使用上面的VBA我能够找到行数。但是,如何查找给定的excel文件中的列数?
您的示例代码获取当前列的最后一个非空白单元格的行号,并可以被重写如下:
Dim lastRow As Long
lastRow = Sheet1.Cells(Rows.Count, 1).End(xlUp).Row
MsgBox lastRow
它是那么容易看到,等效代码来获取当前行中最后一个非空白单元格的列数为:
Dim lastColumn As Long
lastColumn = Sheet1.Cells(1, Columns.Count).End(xlToLeft).Column
MsgBox lastColumn
这也可能是你有帮助:
With Sheet1.UsedRange
MsgBox .Rows.Count & " rows and " & .Columns.Count & " columns"
End With
但请注意,如果列A和/或行1是空白的,那么这将不会产生与上述其他示例相同的结果。有关更多信息,请阅读UsedRange
属性。
嗨。我尝试使用代码 'Dim lastRow As Long lastRow = Sheet1.Cells(Rows.Count,1).End(xlUp).Row MsgBox lastRow' 但VBA在运行时错误424:Object required其中的第二条。 现在我迷路了。哪一个函数确实需要一个对象,它取得了什么? – mzuba
你真的有一个名为'Sheet1'的工作表吗?如果没有,那么这会导致错误。 –
让 - 弗朗索瓦科贝特的答案是完美的。为了详尽,我只想补充与一些限制你也可以使用UsedRange.Columns.Count
或UsedRange.Rows.Count
。
问题是,在删除行/列时(至少在您重新打开工作簿之前),UsedRange并不总是被更新。
是的,我写了'UsedRange'作为事后的使用,只是为了让OP知道这个属性,并且可能提示了一些实验。 –
可能您在columns.count
之前的某处忘记了sheet1
,或者它会计算activesheet
列而不是sheet1
的列。
此外,不应该是xltoleft而不是xltoright? (确定这里很晚,但我认为我知道我的权利从左)我检查了它,你必须写xltoleft。
Dim lastColumn As Long
lastColumn = Sheet1.Cells(1, Columns.Count).End(xlToLeft).Column
MsgBox lastColumn
结果示于下面的代码为信(H,I等:
lastColumn = Sheet1.Cells(1, sheet1.Columns.Count).End(xlToleft).Column
结果在下面的代码作为列号(8,9等)中所示。):
Dim lastColumn As Long
lastColumn = Sheet1.Cells(1, Columns.Count).End(xlToLeft).Column
MsgBox Split(Sheet1.Cells(1, lastColumn).Address, "$")(1)
@niko它不清楚你是否想使用的列(问题的标题),或最后使用的列的位置的号码(由'row'代码暗示的)? – brettdj
@niko,找到表单的实际使用部分而不是'xlUp'变体或者kludgy'UsedRange'的更好方法是'Find'。见http://stackoverflow.com/questions/8283797/select-range-in-excel-vba/8283941#8283941 – brettdj