[英]Excel VBA find duplicates in 1st 2 columns and then sum rows in 3rd & 4th column
[英]Excel VBA - delete every 3rd and 4th column in range
試圖弄清楚如何刪除范圍內的每 3 和 4 列。
我知道我可以刪除范圍內的列:
Columns("C:E").EntireColumn.Delete
但無法弄清楚如何只刪除每第 3 次和第 4 次...
下面的代碼刪除“Sheet1”中的第 3 和第 4 列(根據需要修改工作表的名稱):
Option Explicit
Sub DeleteEvery_ThirdFourthCol()
Dim LastCol As Long
Dim Col As Long
' modify "Sheet1" to your sheet's name
With Sheets("Sheet1")
' find last column with data in row 1 > modify to your needs
LastCol = .Cells(1, .Columns.Count).End(xlToLeft).Column
' loop columns backwards when deleting
For Col = LastCol To 1 Step -1
If Col Mod 3 = 0 Or Col Mod 4 = 0 Then
.Range(.Cells(1, Col), .Cells(1, Col)).EntireColumn.Delete
End If
Next Col
End With
End Sub
正如@YowE3K 之前提到的,目前尚不清楚要求是否為:
因此,我為每種情況提供了一個單獨的解決方案:
這些解決方案會立即刪除工作表UsedRange
中符合要求的所有列。
1.刪除每列是3或4的倍數
Sub Delete_Every_Column_Multiple_Of_3_or_4()
Dim rTrg As Range, iLstCol As Integer, i As Integer
With ThisWorkbook.Sheets("Sht(1)") 'Change as required
iLstCol = .UsedRange.SpecialCells(xlLastCell).Column
For i = 1 To iLstCol
If i <> 1 And (i Mod 3 = 0 Or i Mod 4 = 0) Then
If rTrg Is Nothing Then
Set rTrg = .Columns(i)
Else
Set rTrg = Union(rTrg, .Columns(i))
End If: End If: Next
rTrg.EntireColumn.Delete
End With
End Sub
2.刪除每組4列中的第3和第4列
Sub Delete_3rd_And_4th_Column_in_Every_Group_of_Four()
Dim rTrg As Range
Dim iLstCol As Integer
Dim i As Integer
With ThisWorkbook.Sheets("Sht(2)") 'Change as required
iLstCol = .UsedRange.SpecialCells(xlLastCell).Column
For i = 1 To iLstCol
If i Mod 4 = 0 Or i Mod 4 = 3 Then
If rTrg Is Nothing Then
Set rTrg = .Columns(i)
Else
Set rTrg = Union(rTrg, .Columns(i))
End If: End If: Next
rTrg.EntireColumn.Delete
End With
End Sub
Public Sub DeleteEveryThirdColumn()
Const EveryN As Long = 3
Dim rng As Range: Set rng = ActiveSheet.Range("C:F")
Dim c As Long: For c = ((rng.Columns.Count - 1) \ EveryN) * EveryN + 1 To 1 Step -EveryN
rng.Columns(c).Delete
Next c
End Sub
假設您要刪除列:
3,4,6,7,9,10
只需創建等效的列地址字符串即可:
Sub KolumnKiller()
Range("C:C,D:D,F:F,G:G,I:I,J:J").Delete
End Sub
請注意,這避免了使用循環。
如果需要循環,則應向后運行。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.