使用给定的标题/名称删除列

时间:2019-12-06 15:02:32

标签: excel vba loops

我正在尝试获取一个代码,该代码将允许我从B列开始删除第一行中名为“ delete”的列-意味着第一列的名称不同,为“ hide”,因为在此放置了一些执行更改的命令行(不包含在下面的代码中),因此对我来说重要的是开始从B中删除列。 不幸的是,我的代码删除了以下列:

A(不得删除),B(已删除),C(未删除),D(已删除)E(未删除),甚至我都将B到E都用“删除”命名。

您能提供帮助吗?我必须承认我是一个初学者,我的知识很小:)

代码如下:

Sub deleting()

Dim lcolumn As Long ' column
Dim j As Long

Dim sh As Worksheet, shs As Sheets
Dim wkbTarget As Workbook


For Each sh In ActiveWorkbook.Worksheets ' here's a loop through each sheet

 sh.Select
 With ActiveSheet

        lcolumn = .Cells(1, .Columns.Count).End(xlToLeft).Column

    For j = 1 To lcolumn
                If .Cells(1, j).Value = "delete" Then 'here is something wrong...
                    sh.Columns(j).Delete Shift:=xlShiftToLeft
            End If
    Next j

    End With

        Next sh
End Sub

1 个答案:

答案 0 :(得分:2)

您需要向后迭代,您要删除一列,然后将所有列推向左侧。因此,您将跳过删除每一列的一列。

所以不是

For j = 1 To lcolumn
    If .Cells(1, j).Value = "delete" Then 'here is something wrong...
        sh.Columns(j).Delete Shift:=xlShiftToLeft
    End If
Next j

你想要

for j = lcolumn to 2 step -1 'to 2 because you want to skip column A
   If .Cells(1, j).Value = "delete" Then 
       sh.Columns(j).Delete Shift:=xlShiftToLeft
   End If
Next j