无法匹配列名称

时间:2016-04-29 09:25:05

标签: excel vba excel-vba

我正在搜索列名,但我的代码无效。这就是我的尝试:

    word = "sample"
    Set aCell = ActiveSheet.Rows(1).Find(What:=word, LookIn:=xlValues, _
    LookAt:=xlWhole, SearchOrder:=xlByRows, SearchDirection:=xlNext, _
    MatchCase:=False, SearchFormat:=False)

    lastRow = Cells(1, Columns.count).End(xlToLeft).Column

    For k = 0 To lastRow
        If aCell Is Nothing Then
            aCell.Offset(0, 1).EntireColumn.Delete
        End If
    Next k

我想要做的就是删除整个列(如果找到它)。有什么帮助吗?

4 个答案:

答案 0 :(得分:0)

你可以这样做:

var abc = <column_name>.replace(/[^0-9]/g,'')

答案 1 :(得分:0)

如果要删除标题为“sample”的整列,请在模块中尝试:

Public Sub DeleteSample()

    DeleteColumn ("sample")

End Sub

Public Sub DeleteColumn(Name As String)

    'Get the header row
    Dim row As Range
    Set row = Rows(1)

    'Find the cell containing Name in that row
    Dim result As Range
    Set result = row.Find(Name)

    Dim wholeColumn As Range

    'Select the whole column (or quit if it's not found)

    On Error GoTo Catch
    Set wholeColumn = result.EntireColumn()
    On Error GoTo 0

    'Delete the whole column and shift cells left
    wholeColumn.Delete xlShiftToLeft

Catch:
    Exit Sub

End Sub

您根本不需要For循环,只需使用Excel API查找单元格:)

答案 2 :(得分:0)

Sub columndelete()
    Dim lastcolumn As Long
    word = "sample"
    lastcolumn = Cells(1, Columns.Count).End(xlToLeft).Column
    For i = 1 To lastcolumn
        If Cells(1, i).Value = word Then
            Cells(1, i).EntireColumn.Delete
        End If
    Next i
End Sub

答案 3 :(得分:0)

刚刚对代码进行了一些更改:

Sub test()
    word = "sample"
    Set acell = ActiveSheet.Rows(1).Find(What:=word, LookIn:=xlValues, _
    LookAt:=xlWhole, SearchOrder:=xlByRows, SearchDirection:=xlNext, _
    MatchCase:=False, SearchFormat:=False)

    If Not (acell Is Nothing) Then
        acell.EntireColumn.Delete
    End If
End Sub