vba 如何在VBA中查找和选择最后一列?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17730639/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to find and select the last column in VBA?
提问by Joe Gay
I am trying to create an excel macro which finds the last column of a sheet and then selects the entire column. However, this column will always be different- some days it will be column 'H', other days will be column 'GX' as the data in the sheet is constantly updated. So far I have seen how you can find the last column and then delete it, but it specifically refers to that certain column once the macro runs again. I need it to always refer to the last column, no matter what column that may be. Thanks!
我正在尝试创建一个 excel 宏,它找到工作表的最后一列,然后选择整列。但是,此列总是不同的 - 有时它会是“H”列,而另一些天会是“GX”列,因为工作表中的数据会不断更新。到目前为止,我已经看到了如何找到最后一列然后将其删除,但是一旦宏再次运行,它就特指该特定列。我需要它总是引用最后一列,无论是哪一列。谢谢!
Here is the code. I am new to VBA, etc. and this was created through the macro recorder and other things I found online so bear with me!
这是代码。我是 VBA 的新手,等等,这是通过宏记录器和我在网上找到的其他东西创建的,所以请耐心等待!
`Sub Macro11()
Sheets("Sheet25").Cells(1, 1).Activate
ActiveCell.SpecialCells(xlLastCell).Select
lastCol = ActiveCell.Column
Columns("W:W").Select
Selection.Delete Shift:=xlToLeft
End Sub`
回答by Santosh
Here is the sample code
Avoid using Select /Activate in your code. To know why refer this link
这是示例代码
避免在代码中使用 Select /Activate。要知道为什么参考此链接
Sub Macro11()
Dim LastCol As Long
With ThisWorkbook.Sheets("Sheet25")
LastCol = .Cells(1, .Columns.Count).End(xlToLeft).Column
.Columns(LastCol).Delete
End With
End Sub