Excel VBA删除一行中的特定列

标签 excel vba

我正在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
我收到运行时错误。为什么?
编辑说明:
Image of what I have and What i need
我需要在第 2 行中搜索“名称”并将 I、J、K 等列中的所有值提取到 E 列。所以我需要删除 E 到 H 列并仅针对给定移动列 I、J 等排。不应删除其他行的列。

最佳答案

删除之前的列

  • 在开发删除行或列的代码时,最好使用 Select而不是 Delete ,并且只有在代码完成后,才切换到 Delete .
  • ResizeOffset将准确定义搜索范围。
  • 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/

    相关文章:

    sql - 将多个 Excel 文件导入 SQL Server

    arrays - Excel VBA - 将公式结果分配给数组

    sql-server - 'AvayaSBCCRT' 附近的语法不正确

    arrays - 用数组填充下拉列表

    excel - 取消选择表单控件列表框中的所有项目

    excel - 如何根据条件连接多个单元格中的值?

    excel - 更改 Excel 中 TODAY() 的格式

    excel - 使用 EXCEL 将十六进制字符转换为 ASCII 字符

    excel - 检查 MS Excel 中的两行是否完全相同

    VBA IsNumeric 在特定字符串上失败?