VBA:如何在特定列标题之后对所有内容执行操作?

时间:2018-11-16 00:32:24

标签: excel vba excel-vba

我试图编写VBA代码以查找特定的列标题(“主列”),然后删除该列之后的不需要的列,但删除该列之前的任何内容。我该如何写我的if陈述?我知道如何删除不相关的列,但只删除整个工作表,而不删除特定列标题后面的列。

3 个答案:

答案 0 :(得分:0)

您应该可以使用以下代码作为您尝试做的踏脚石:

Sub DeleteColumns()

    Dim rng As Range, c As Range
    Dim str As String

    str = "Master Column"
    Set rng = ActiveSheet.Rows(1)
    Set c = rng.Find(str, LookIn:=xlValues)

    With ActiveSheet
        .Range(.Cells(1, c.Column + 1), .Cells(1, .Columns.Count)).EntireColumn.Delete
    End With

End Sub

答案 1 :(得分:0)

  1. 找到最后使用的标题列(假设标题位于Row 1上)并将值存储在变量LCol
  2. 使用带有字符串变量Range.Find的{​​{1}}和
  3. 查找主列
  4. 检查是否实际找到了Header。如果,则显示消息和Header
  5. 如果找到Exit Sub,则使用Header遍历其余的列到Header.Column

如果您要在之后 主列开始,您将使用LCol


For i = Found.Column + 1 to LCol

根据要求,该宏仅在主列之后(包括之后)循环遍历各列。我只是在更改循环内的颜色。您可以更新它以相当容易地删除列。该代码还处理找不到目标列的事件(请参见上一张照片)

enter image description here

enter image description here

enter image description here

您将要修改Option Explicit Sub Header_() Dim ws As Worksheet: Set ws = ThisWorkbook.Sheets("Sheet1") '<-- Update Sheet Name Dim LCol As Long, i As Long Dim Found As Range Dim Header As String Header = "Master Column" LCol = ws.Cells(1, ws.Columns.Count).End(xlToLeft).Column Set Found = ws.Range(ws.Cells(1, 1), ws.Cells(1, LCol)).Find(Header) If Found Is Nothing Then MsgBox "Column Header " & Chr(34) & Header & Chr(34) & " Not Found" Exit Sub End If For i = Found.Column To LCol ws.Cells(1, i).Interior.Color = vbYellow Next i End Sub 上的选项。您可以查看选项here

答案 2 :(得分:0)

在之后删除列

决定删除哪些列的方式只有无数种,所以我选择了一种。

删除标题中包含指定字符串的所有列

在此代码示例ActiveWorkbook中,已使用ActiveSheet和“ DEL”字符串以及快速版本。您可以在“常量”部分中进行更改。
快速版本通过计算一个范围来解决该问题,该范围随后将一次性删除列,而慢版本则逐个删除列。

'*******************************************************************************
' Purpose:  Deletes only columns appearing after a specified column AND
'           containing a specified string in their header.
'*******************************************************************************
Sub DeleteColumnsAfter()

  Const cStrWB As String = "" ' e.g. "Master.xls", if "" then ActiveWorkbook.
  Const cStrWS As String = "" ' e.g. "Sheet1", if "" then Activesheet.
  Const cStrStart As String = "Master Column" ' Search Column Title
  Const cStrSearch As String = "DEL" ' Search String ("" for all columns.)
  Const cBlnFast As Boolean = True ' False for deleting column by column.

  Dim objWs As Worksheet  ' Worksheet to be processed.
  Dim objStart As Range   ' Cell range after which columns are to be deleted.
  Dim objEnd As Range     ' Last cell range in objSearch.
  Dim objSearch As Range  ' Range where cStrSearch will be searched for.
  Dim objDEL As Range     ' Range to be deleted.
  Dim intCol As Integer   ' Columns Counter
  Dim strError As String  ' Error Help String

  ' Determine the worksheet to be processed.
  On Error GoTo WsHandler
    If cStrWB = "" Then ' Unspecified workbook
      If cStrWS = "" Then ' Unspecified worksheet
        Set objWs = ActiveWorkbook.ActiveSheet
       Else ' Specified worksheet
        Set objWs = ActiveWorkbook.Worksheets(cStrWS)
      End If
     Else ' Specified workbook
      If cStrWS = "" Then ' Unspecified worksheet
        Set objWs = Workbooks(cStrWB).ActiveSheet
       Else ' Specified worksheet
        Set objWs = Workbooks(cStrWB).Worksheets(cStrWS)
      End If
    End If
  On Error GoTo 0

  With objWs
    ' Find the cell range containing cStrStart.
    Set objStart = .Cells.Find(what:=cStrStart, _
        After:=.Cells(.Rows.Count, .Columns.Count), LookIn:=xlFormulas, _
        Lookat:=xlWhole, SearchOrder:=xlByRows, SearchDirection:=xlNext)
    ' Check if cStrStart is not found.
    If objStart Is Nothing Then GoTo StartExit

    ' Find the last non-empty cell in the row of objStart.
    Set objEnd = .Cells.Find(what:="*", _
        After:=.Cells(objStart.Row + 1, 1), LookIn:=xlFormulas, _
        Lookat:=xlWhole, SearchOrder:=xlByRows, SearchDirection:=xlPrevious)

    ' Determine the range where cStrSearch is to be searched for.
    Set objSearch = .Range(objStart.Offset(0, 1), objEnd)

    If cBlnFast = True Then ' Fast Version

      ' Determine the first cell where cStrSearch is found.
      For intCol = 1 To objSearch.Cells.Count
        ' cStrSearch IS found (vbTextCompare i.e. case-insensitive e.g. DEL=Del)
        If InStr(1, objSearch(intCol).Text, cStrSearch, vbTextCompare) <> 0 Then
          ' Creating a reference to the cell where cStrSearch is found.
          ' Other cells will be added in the following For Next loop creating
          ' the range whose columns will be deleted.
          Set objDEL = .Cells(1, objSearch.Column + intCol - 1)
          ' Resize search range to a range starting after the found cStrSearch.
          Set objSearch = .Range(objStart.Offset(0, intCol + 1), objEnd)
          Exit For
        End If
      Next
      ' Check if cStrSearch is not found.
      If objDEL Is Nothing Then GoTo ColumnsHandler

      ' Add the rest of the cells where cStrSearch is found.
      For intCol = 1 To objSearch.Cells.Count
        If InStr(1, objSearch(intCol).Text, cStrSearch, vbTextCompare) <> 0 Then
          ' This wouldn't have worked before because objDEL was Nothing.
          Set objDEL = Union(objDEL, .Cells(1, objSearch.Column + intCol - 1))
        End If
      Next

      ' Delete the columns.
      objDEL.EntireColumn.Delete
      ' Tip: Replace Delete with Select or Hide for testing.

     Else ' SLow Version (cBlnFast = False)

      For Each objDEL In objSearch

        ' cStrSearch IS found (vbTextCompare i.e. case-insensitive e.g. DEL=Del)
        If InStr(1, objDEL.Text, cStrSearch, vbTextCompare) <> 0 Then _
        objDEL.EntireColumn.Delete
        ' Tip: Replace Delete with Select or Hide for testing.

      Next

    End If ' cBlnFast

  End With ' Worksheet

ProcedureExit:
  Set objDEL = Nothing
  Set objSearch = Nothing
StartExit:
  Set objStart = Nothing
WsExit:
  Set objWs = Nothing
Exit Sub

' Errors
ColumnsHandler:
  MsgBox "No columnns to delete."
  GoTo ProcedureExit
StartHandler:
  MsgBox "Could not find '" & cStrStart & "' in worksheet '" & objWs.Name & "'."
  GoTo StartExit
WsHandler:
  MsgBox "Something went wrong with the Worksheet or the Workbook."
  GoTo WsExit

End Sub