我没有看到Union的相关性,所以我希望我没有误解你的要求。
第一个任务是确定最后一行和最后一列。有多种技术可以找到最后一行或最后一列;没有一个在任何情况下都有效。我相信SpecialCells最适合这种情况。
当我不确定如何实现某个目标时,我将其分解为小任务,编码任务 1 并使用Debug.Print 将诊断信息输出到即时窗口。当我让任务 1 工作时,我将任务 2 的代码与新的诊断信息一起添加。所以我的第一个宏,Demo1 只输出最后一行和最后一列。尝试将值放在任何现有值的左侧或下方,以查看宏输出的内容。
注意:我很少提及我正在使用的语句。一般来说,一旦你知道它存在,就很容易查找它。如有必要,请回来提出问题,但请先尝试自己的调查。
Option Explicit
Sub Demo1()
Dim ColLast As Long
Dim RowLast As Long
' Replace "Source" with the name of your worksheet
With Worksheets("Source")
ColLast = Cells.SpecialCells(xlCellTypeLastCell).Column
RowLast = Cells.SpecialCells(xlCellTypeLastCell).Row
End With
Debug.Print "Last column " & ColLast
Debug.Print "Last row " & RowLast
' Note Cells(RowLast, ColLast) does not have to contain a value.
End Sub
下一个任务是确定要删除的列。我使用工作表函数CountIf 从第 4 列(即“D”列)开始计算每列中 2 和 3 的数量。
Sub Demo2()
Dim ColCrnt As Long
Dim ColLast As Long
Dim Rng As Range
Dim RowLast As Long
With Worksheets("Source")
ColLast = Cells.SpecialCells(xlCellTypeLastCell).Column
RowLast = Cells.SpecialCells(xlCellTypeLastCell).Row
For ColCrnt = 4 To ColLast
Set Rng = .Range(.Cells(1, ColCrnt), .Cells(RowLast, ColCrnt))
Debug.Print ColCrnt;
Debug.Print " Num 2s=" & WorksheetFunction.CountIf(Rng, 2);
Debug.Print " Num 3s=" & WorksheetFunction.CountIf(Rng, 3)
Next
End With
End Sub
最后的任务是删除没有2s和3s的列。对于Demo2,我使用了 For 循环。 For-Loop 的问题是您不能在循环中更改 End Value,我们需要在删除列时这样做。所以对于Demo3,我必须使用Do-Loop。
Sub Demo3()
Dim ColCrnt As Long
Dim ColLast As Long
Dim Rng As Range
Dim RowLast As Long
With Worksheets("Source")
ColLast = Cells.SpecialCells(xlCellTypeLastCell).Column
RowLast = Cells.SpecialCells(xlCellTypeLastCell).Row
ColCrnt = 4
Do While ColCrnt <= ColLast
Set Rng = .Range(.Cells(1, ColCrnt), .Cells(RowLast, ColCrnt))
If WorksheetFunction.CountIf(Rng, 2) + _
WorksheetFunction.CountIf(Rng, 3) > 0 Then
' This column contains a 2 or a 3. Do not delete column.
' Advance to next column
ColCrnt = ColCrnt + 1
Else
' This column does not contain a 2 or 3. Delete column.
.Columns(ColCrnt).EntireColumn.Delete
' Reduce ColLast to allow for deletion.
ColLast = ColLast - 1
End If
Loop
End With
End Sub
希望以上内容有所帮助。