1

I am trying to add a button, that adds a new column after the last column with values. This works.

Now I want to copy values to the new column. Values shall be copied from the last column from row 32 to the last one with a value in column A. Right now Ihave a code for copying the whole column. How do I concentrate on the specific range?

Sub AddMeeting()
Dim ws As Worksheet
Dim lastcol As Long
 Set ws = ActiveSheet

lastcol = ws.Cells(32, ws.Columns.Count).End(xlToLeft).Column
Columns(lastcol).Copy Destination:=Columns(lastcol + 1)
Range ((Cells.Columns.Count.End(xlLeft)) & Range(32)), (lastcol + 1) & Cells.Rows.Count.End(xlUp)



 Application.CutCopyMode = False
End Sub
Siddharth Rout
  • 147,039
  • 17
  • 206
  • 250

1 Answers1

1

Values shall be copied from the last column from row 32 to the last one with a value in column A

Is this what you are trying?

Option Explicit

Sub Sample()
    Dim ws As Worksheet
    Dim lRow As Long, lCol As Long
    Dim LastColumn As String
    Dim rngToCopy As Range

    '~~> Set this to the relevant worksheet
    Set ws = Sheet1

    With ws
        '~~> Find last row in Col A
        lRow = .Range("A" & .Rows.Count).End(xlUp).Row
        '~~> Find last column in row 32
        lCol = .Cells(32, .Columns.Count).End(xlToLeft).Column
        '~~> Get Column Name from column number
        ' https://stackoverflow.com/questions/10106465/excel-column-number-from-column-name
        LastColumn = Split(Cells(, lCol).Address, "$")(1)

        Set rngToCopy = .Range("A32:" & LastColumn & lRow)

        Debug.Print rngToCopy.Address

        With rngToCopy
            '
            '   Do what you want here
            '
        End With
    End With
End Sub
Siddharth Rout
  • 147,039
  • 17
  • 206
  • 250
  • okay i feel ashamed for struggling for an hour straight and you just solving it within minutes lol...works perfectly. –  Feb 26 '20 at 12:52
  • 1
    No need to feel ashamed. Happens to most of us :) – Siddharth Rout Feb 26 '20 at 12:53
  • Set rngToCopy = .Range("A32:" & LastColumn & lRow) can i change the A32 to something with Lastcolumn & 32 for example? –  Feb 26 '20 at 13:02
  • 1
    Remember a range say `"A32:X40"` can be written as `"A" & "32" & ":" & "X" & "40"`. You can simply replace those values with variables :) – Siddharth Rout Feb 26 '20 at 13:03
  • 1
    Yes the variable when put between quotes behave as string... try this `LastColumn & "32" & ":" & LastColumn & LastRow` or `LastColumn & "32:" & LastColumn & LastRow` – Siddharth Rout Feb 26 '20 at 13:06
  • hey :) could you check my original question? editted it with your code. I need somethig additional to this. maybe you can help ? –  Feb 28 '20 at 11:56
  • New question = New post. Please do not edit the old question. :) Create a new post and post the link here. If no one else answers it and if I am online, I will have a look at it. – Siddharth Rout Feb 28 '20 at 12:21