Avatar of Edward Pamias
Edward PamiasFlag for United States of America asked on

Excel Macro to copy Multiple Columns and dynamic rows

Hi All,

Here is a simple macro I created. I have a fixed number of columns and the rows change daily. I need a macro to copy from one sheet to another.

Sub Macro1()
'
' Macro1 Macro
'
' Keyboard Shortcut: Ctrl+Shift+G
'
    Range("A1:C17").Select
    Selection.Copy
    Sheets("Sheet1").Select
    Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
        :=False, Transpose:=False
End Sub
Microsoft Excel

Avatar of undefined
Last Comment
Edward Pamias

8/22/2022 - Mon
SixSigmaGuy

Not really sure what your question is.  Are you saying that the NUMBER of rows change?  If so, then here's your answer.  I'm making assumptions here that the first row is always row 1; so you'll need to modify that isn't the case.  I'm also assuming that column 1 contains data for every row.  You'll need to modify if that isn't the case either.

Sub Macro1()
'
' Macro1 Macro
'
' Keyboard Shortcut: Ctrl+Shift+G
'
    iLastRow = iLastRowFilledInColumn(Me, 1)  ' see my function below
    stRange = "A1:C" & iLastRow
    Range(stRange).Select
    Selection.Copy
    Sheets("Sheet1").Select
    Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
        :=False, Transpose:=False
End Sub

Function iLastRowFilledInColumn(ws As Excel.Worksheet, iColumn As Long) As Long
    Dim iLastRow As Long
   
    iLastRow = ws.Cells(ws.Rows.Count, iColumn).End(xlUp).Row
    '
    ' If the entire column is empty, Excel still returns 1 even though
    ' there is no data in row 1.  Therefore, check to see if the
    ' cell is empty; if it is, return 0 instead of 1.
    '
    If iLastRow = 1& Then
        If Trim(ws.Cells(iLastRow, iColumn)) = "" Then
            iLastRow = 0&
        End If
    End If
   
    iLastRowFilledInColumn = iLastRow
End Function
ASKER CERTIFIED SOLUTION
byundt

Log in or sign up to see answer
Become an EE member today7-DAY FREE TRIAL
Members can start a 7-Day Free trial then enjoy unlimited access to the platform
Sign up - Free for 7 days
or
Learn why we charge membership fees
We get it - no one likes a content blocker. Take one extra minute and find out why we block content.
See how we're fighting big data
Not exactly the question you had in mind?
Sign up for an EE membership and get your own personalized solution. With an EE membership, you can ask unlimited troubleshooting, research, or opinion questions.
ask a question
ASKER
Edward Pamias

This code worked perfectly. The previous post gave me errors. Thanks to both for the assistance. I will have another question soon. Similar to this one.
Experts Exchange is like having an extremely knowledgeable team sitting and waiting for your call. Couldn't do my job half as well as I do without it!
James Murphy