+ Reply to Thread
Results 1 to 2 of 2

Insert Column before a cell with Specific value

Hybrid View

  1. #1
    Registered User
    Join Date
    08-30-2012
    Location
    Kampala
    MS-Off Ver
    Excel 2007
    Posts
    1

    Unhappy Insert Column before a cell with Specific value

    Hi everyone,
    I want to create a command button that adds a column be4 a specified value every time is clicked.
    I figured i might just search the row containing this value "Targets" and return is index, then use that
    index as a basis to insert a new column.
    I do find the target and its index , but it is not inserting my column.
    I know there could be better code more guaranteed to work. some body can help.
    Private Sub CommandButton2_Click()
    Dim rng(5 To 25) As Variant, K As Integer
    ' dynamically assign the entire value of ranges to the array
    For K = 5 To 25 'search from C to Z
    rng(K) = Cells(5, K).Value
    If (rng(K) = "Targets") Then
     Columns((K + 4)).Insert
     Debug.Print K
     Debug.Print rng(K)
     End If
     Next K
     End Sub
    All the Best

  2. #2
    Forum Guru HaHoBe's Avatar
    Join Date
    02-19-2005
    Location
    Hamburg, Germany
    MS-Off Ver
    work: 2016 on Win10 (notebook), private: 365 on Win11 (desktop), 2019 on Win11 (notebook)
    Posts
    8,198

    Re: Insert Column before a cell with Specific value

    Hi, Tryagainandagain,

    please check and change both SheetName and range if they do not fit your request:

    Private Sub CommandButton2_Click()
    Dim rngFound As Range
    
    Set rngFound = Sheets("Sheet1").Range("E5:Y5").Find(What:="Targets", _
        SearchOrder:=xlByColumns, _
        SearchDirection:=xlNext, _
        MatchCase:=True, _
        SearchFormat:=False)
    
    If Not rngFound Is Nothing Then
      rngFound.EntireColumn.Insert
    End If
    
    Set rngFound = Nothing
    End Sub
    Ciao,
    Holger

+ Reply to Thread

Thread Information

Users Browsing this Thread

There are currently 1 users browsing this thread. (0 members and 1 guests)

Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts

Search Engine Friendly URLs by vBSEO 3.6.0 RC 1