Excel VBA循环工作表:ActiveWorkbook.Worksheets(I)?
昨天我决定学习一些VBA,使我的Excel时间更容易。 现在已经有所好转了,但是现在我已经在这个代码上打了好几个小时了。
我试图删除所有空(除标题)列,并在工作簿的所有表中。 大量的谷歌search后,我设法find一些例子,我可以适应我的需要。
我使用这个代码: 删除列 ,然后试图循环通过使用亲爱的旧的微软支持表
我一起frankensteined到这个:
Sub WorksheetLoop() Dim WS_Count As Integer Dim I As Integer Dim MyRange As Range Dim iCounter As Long WS_Count = ActiveWorkbook.Worksheets.Count For I = 1 To WS_Count 'removecode ' Define the target Range. Set MyRange = ActiveWorkbook.Worksheets(I).UsedRange 'Start reverse looping through the range. For iCounter = MyRange.Columns.Count To 1 Step -1 'If entire column is empty then delete it. If Application.CountA(Columns(iCounter).EntireColumn) = 1 Then Columns(iCounter).Delete End If Next iCounter 'endremovecode MsgBox ActiveWorkbook.Worksheets(I).Name Next I End Sub
当我运行这个,只有起始工作表被清理。 该消息框会循环所有这些。
为什么? 我究竟做错了什么? 我试图find一个解决scheme,但这里的主题似乎没有更清晰。
感谢一群领导我正确的方向。
拉拉
Columns(iCounter).EntireColumn
和
Columns(iCounter).Delete
没有用MyRange
作为前缀,因此请参考活动工作表的列而不是包含MyRange
的工作表。 粘MyRange.
他们的前面。
你快到了。 你只需要限定你的application.counta
和你的.columns().delete.
所以每个人都直接与有问题的表单工作。 否则,它只是使用活动工作表。
尝试这个:
Sub WorksheetLoop() Dim WS_Count As Integer Dim I As Integer Dim MyRange As Range Dim iCounter As Long Dim ws As Worksheet WS_Count = ActiveWorkbook.Worksheets.Count For I = 1 To WS_Count Set ws = ActiveWorkbook.Worksheets(I) 'removecode With ws ' Define the target Range. Set MyRange = .UsedRange 'Start reverse looping through the range. For iCounter = MyRange.Columns.Count To 1 Step -1 'If entire column is empty then delete it. If Application.CountA(.Columns(iCounter).EntireColumn) = 0 Then .Columns(iCounter).Delete End If Next iCounter End With 'endremovecode MsgBox ws.Name Next I End Sub