Find Column Header By Name And Select All Data Below Column Header (Excel-VBA)

前端 未结 5 1522
予麋鹿
予麋鹿 2020-12-06 07:42

This is my first post...

I\'m attempting to create a macro to do the following:

  1. Search a spreadsheet column header by name.
  2. Select all data fr
5条回答
  •  借酒劲吻你
    2020-12-06 08:32

    It is good to avoid looping through all cells. If the data set grows the macro can become too slow. Using special cells and paste special operation of multiplying by 1 is an efficient way of accomplishing the task.

    This works...

    Dim SelRange As Range
    Dim ColNum As Integer
    Dim CWS As Worksheet, TmpWS As Worksheet
    
    'Find the column number where the column header is
    Set CWS = ActiveSheet
    ColNum = Application.WorksheetFunction.Match("Employee ID", CWS.Rows(1), 0)
    
    'Set the column range to work with
    Set SelRange = CWS.Columns(ColNum)
    
    'Add a worksheet to put '1' onto the clipboard, ensures no issues on activesheet
    Application.ScreenUpdating = False
    Application.DisplayAlerts = False
    
        Set TmpWS = ThisWorkbook.Worksheets.Add
        With TmpWS
            .Cells(1, 1) = 1
            .Cells(1, 1).Copy
        End With
    
        'Select none blank cells using special cells...much faster than looping through all cells
        Set SelRange = SelRange.SpecialCells(xlCellTypeConstants, 23)
        SelRange.PasteSpecial Paste:=xlPasteAll, Operation:=xlMultiply
        TmpWS.Delete
        CWS.Select
    
    Application.DisplayAlerts = True
    Application.ScreenUpdating = True
    

提交回复
热议问题