我正在excel中的一行中搜索一个名称。我想删除该名称之前的所有列,直到特定列
例如。我的名字在第 10 列,我想删除从第 2 列到第 9 列的所有内容,以便我的名字的第 10 列将位于第 2 列的位置。
Sub delete_cells()
Dim rg As Range
Set rg = ActiveSheet.Rows(2).Find(What:="Name", LookIn:=xlValues, LookAt:=xlWhole, _
SearchOrder:=xlByRows, MatchCase:=False)
If Not rg Is Nothing Then
If rg.Column > 1 Then ActiveSheet.Columns("4:" & rg.Column - 3).Delete
Else
MsgBox "Something
End If
End Sub
我收到运行时错误。为什么?编辑说明:
我需要在第 2 行中搜索“名称”并将 I、J、K 等列中的所有值提取到 E 列。所以我需要删除 E 到 H 列并仅针对给定移动列 I、J 等排。不应删除其他行的列。
最佳答案
删除之前的列
Select
而不是 Delete
,并且只有在代码完成后,才切换到 Delete
. Resize
和 Offset
将准确定义搜索范围。 LookIn
参数xlFormulas
将允许在隐藏列中查找事件。 After
的参数论据,.Cells(.Cells.Count)
(定义最后一个单元格)将使搜索从范围的第一个单元格开始。 代码
Option Explicit
Sub deleteColumns()
Const cRow As Long = 2
Const cCol As Long = 2
Const Criteria As String = "Name"
Dim ws As Worksheet: Set ws = ActiveSheet
Dim fCell As Range
With ws.Rows(cRow)
Set fCell = .Resize(, .Columns.Count - cCol).Offset(, cCol) _
.Find(Criteria, .Cells(.Cells.Count), xlFormulas, xlWhole)
End With
If Not fCell Is Nothing Then
ws.Columns(cCol).Resize(, fCell.Column - cCol).Select ' .Delete
Else
MsgBox "Could not find '" & Criteria & "'.", vbExclamation, "Not Found"
End If
End Sub
编辑:Sub deleteColumns()
Const cRow As Long = 2
Const cCol As Long = 4
Const Criteria As String = "Name"
Dim ws As Worksheet: Set ws = ActiveSheet
Dim fCell As Range
With ws.Rows(cRow)
Set fCell = .Resize(, .Columns.Count - cCol).Offset(, cCol) _
.Find(Criteria, .Cells(.Cells.Count), xlFormulas, xlWhole)
If Not fCell Is Nothing Then
.Columns(cCol).Resize(, fCell.Column - cCol).Delete xlToLeft
Else
MsgBox "Could not find '" & Criteria & "'.", _
vbExclamation, "Not Found"
End If
End With
End Sub
您可以将 cRow 放在参数部分:Sub deleteColumns(ByVal cRow As Long)
并删除 Const cRow As Long = 2
行.然后你可以使用
deleteColumns(i)
在另一个过程的循环中。
关于Excel VBA删除一行中的特定列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66689584/