[英]Delete all columns except ones containing X value
I am trying to delete all columns except names currently the code below deletes names.我正在尝试删除除名称之外的所有列,当前下面的代码将删除名称。
Private Sub CommandButton2_Click()
Dim i As Integer
Dim A As Range
For i = 100 To 1 Step -1
Set A = Cells(1, i).Find(What:="Names", LookIn:=xlValues)
If Not A Is Nothing Then A.EntireColumn.Delete
Next i
End Sub
Updated Code:更新代码:
Private Sub CommandButton1_Click()
Dim i As Integer
Dim A As Range
If Cells(1, i) <> "Names" Then
If A Is Nothing Then A.EntireColumn.Delete
End If
End Sub
I cannot believe there is not a more efficient way, but this should work.我不敢相信没有更有效的方法,但这应该可行。
To allow for the Names column being anywhere, first I move it to column 1 before deleting everything else.为了允许 Names 列在任何地方,首先我将它移动到第 1 列,然后再删除其他所有内容。 The 100 is hard-coded so you may wish to change that.
100 是硬编码的,因此您可能希望更改它。
Private Sub CommandButton1_Click()
Dim i As Long 'better than integer
Dim A As Range
Set A = Rows(1).Find(What:="Names", LookIn:=xlValues, Lookat:=xlWhole, MatchCase:=False, SearchFormat:=False)
If Not A Is Nothing Then 'Names found
Columns(A.Column).Cut
Range("A1").Insert
Range("B1").Resize(, 99).EntireColumn.Delete
Else
Range("A1").Resize(, 100).EntireColumn.Delete 'delete all columns as Names not found
End If
End Sub
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.