[英]Excel VBA delete specific columns in one row
我正在 excel 中的一行中搜索一个名称。 我想删除该名称之前的所有列,直到特定列例如我的名字在第 10 列中,我想删除从第 2 列到第 9 列的所有列,以便我的名字的第 10 列将位于第 2 列的 position。
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 等排。 不应删除其他行的列。
columns
的参数可以是
Columns("B")
Columns(2)
Columns("B:AA")
但是,不能传递用冒号分隔的两个数字: Columns("2:4")
无效。
我认为对您来说最简单的方法是使用resize
方法:
Sub delete_cells(findName As String)
const firstColToDelete = 2 ' (you have 4 in your code, change as you need)
Dim rg As Range
Set rg = ActiveSheet.Rows(2).Find(what:=findName, LookIn:=xlValues, LookAt:=xlWhole, SearchOrder:=xlByRows, MatchCase:=False)
If Not rg Is Nothing Then
Dim colsToDelete As Range
Set colsToDelete = ActiveSheet.Columns(firstColToDelete).Resize(, rg.Column - firstColToDelete)
colsToDelete.Delete
Else
MsgBox "Something"
End If
End Sub
更新:要从 header 行(第 2 行)中删除列,请将代码更改为
Dim colsToDelete As Range
Set colsToDelete = ActiveSheet.Cells(2, firstColToDelete).Resize(, rg.Column - firstColToDelete)
colsToDelete.Delete xlShiftToLeft
请注意,这将使您最右边的数据列没有 header。 这是你的意图吗?
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 放入 arguments 部分:
Sub deleteColumns(ByVal cRow As Long)
并删除Const cRow As Long = 2
行。
然后你可以在另一个过程的循环中使用deleteColumns(i)
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.