Find Last Row use in VBA code with array, File browser and Copy/Paste between workbooks

Rowland Hamilton

Active Member
Joined
Nov 13, 2009
Messages
250
Folks:

Nories code worked great for me when my data was contiguous and
I finally got my adjusted find last row formula to work but I can't seem to get it to work inside my macro with other variables.

Note: My previous copy data was contiguous 1 region but now I need to copy non-contiguous copy data with the parameters in this code (B1:M & lastrow)


Also, I want to use an array for worksheets so that its easier to add and remove cost centers. (2nd priority to first problem)

Finally, if I can get this licked, I'll need a separate macro with a formula for first row, since I have another set of data that resides below a table I don't need. (3rd priority, if lastrow works firstrow should work)

Thank you - Rowland

This worked:
START CODE:
Code:
Sub testing123()
 Dim LastRow As Long
 
 With Worksheets("4050CC30001")
    LastRow = Worksheets("4050CC30001").Cells(Rows.Count, "B").End(xlUp).Row
    .Range(Cells(1, 2), Cells(LastRow, 13)).Select
 End With
 End Sub
END CODE


Now how do I get that to work within this:
START CODE:
Code:
'Completed Code – Sample CC
Option Explicit
Sub Populate_line_item_Workbook_Browser_Method()
Dim MasterWB As Workbook
Dim SourceWB As Workbook
Dim rngSrc As Range
Dim rngDst As Range
Dim ws As Worksheet
Dim varFileName As Variant
Dim I As Long
Dim myArr As Variant
Dim LastRow As Long
Set MasterWB = Workbooks("Line items-Combined16.xlsm")
 
 ''''''''''Clear MasterWB'''''''''''''''''''''''''''''''''''''''''''''''''''''
    MasterWB.Sheets("Master-Incoming").Activate
       Rows("3:3").Select
    Range("E3").Activate
    Range(Selection, ActiveCell.SpecialCells(xlLastCell)).Select
    Selection.ClearContents
    Range("a1").Activate
 '''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
‘"4050CC30001", "301AA1234", "50BB9999" and "65961LL3201"
myArr = Array("4050CC30001", "301AA1234", "50BB9999", "65961LL3201")
'For I = LBound(myArr) To UBound(myArr) – Don’t know how to make array work
 
    varFileName = Application.GetOpenFilename(, , "Please select source workbook:")
    If TypeName(varFileName) = "String" Then
 
        Set SourceWB = Workbooks.Open(Filename:=varFileName, UpdateLinks:=0)
 
        For Each ws In SourceWB.Worksheets
 
            If ws.Name Like "4050CC30001" And ws.Visible <> xlSheetHidden Or _
            ws.Name Like "301AA1234" And ws.Visible <> xlSheetHidden Or _
            ws.Name Like "50BB9999" And ws.Visible <> xlSheetHidden Or _
            ws.Name Like "65961LL3201" And ws.Visible <> xlSheetHidden Then
 
                    'Expand Column groups, Collapse Row groups – need to hide lower table
                ActiveSheet.Outline.ShowLevels RowLevels:=1, ColumnLevels:=2
 
                'copy
               ‘This works for contiguous data region, but my new data is not contiguous:
               ‘Set rngSrc = ws.Range("A3").CurrentRegion.Offset(1, 0)                        
 
      LastRow = ws.Cells(Rows.Count, "B").End(xlUp).Row
 
     ‘I can’t get this to work:                 
    Set rngSrc = ws.Range(Cells(1, 2), Cells(LastRow, 13))
                'paste
                Set rngDst = MasterWB.Sheets("Master-Incoming").Range("A" & Rows.Count).End(xlUp).Offset(1)
 
                 rngSrc.Copy
                 rngDst.PasteSpecial Paste:=xlPasteValues
                 Application.CutCopyMode = False
            End If
         Next ws
         SourceWB.Close False
 
‘On contiguous data, got error message when it ran out of new sheets so I _ 
added MsgBoxes:
        MsgBox "Copied all data from source workbook"
    Else
        MsgBox "No file selected"
    End If
    Application.Goto MasterWB.Worksheets("Master-Incoming").Range("A1"), True
End Sub
END CODE

Key words: Last Row, VBA, Array, Dim, File browser, Copy/Paste between workbooks

Subject: Find Last Row use in VBA code with array, File browser and Copy/Paste between workbooks
 

Excel Facts

Why does 9 mean SUM in SUBTOTAL?
It is because Sum is the 9th alphabetically in Average, Count, CountA, Max, Min, Product, StDev.S, StDev.P, Sum, VAR.S, VAR.P.
Change this...
Set rngSrc = ws.Range(Cells(1, 2), Cells(LastRow, 13))

To this...
Set rngSrc = ws.Range(ws.Cells(1, 2), ws.Cells(LastRow, 13))

Or this...
Set rngSrc = ws.Range("B1:M" & LastRow)
 
Last edited:
Upvote 0
Alphafrog:
I couldn't get either one of these to work:
Code:
               Set rngSrc = ws.Range("B1:M" & LastRow)
nor this:
Code:
               Set rngSrc = ws.Range(ws.Cells(1, 2), ws.Cells(LastRow, 13))
Thank you - Rowland
 
Upvote 0
Could you better explain what you mean by it doesn't work?
  • Does the code error? If yes, what's the error?
  • Does it copy the wrong range? If yes, to big or to small?
  • Does it do nothing?
  • Could you better explain how your data is grouped on the worksheets.

As a test, does this work?
Code:
Sub testing123()
 Dim LastRow As Long
 
 With Worksheets("4050CC30001")
 
    [COLOR="Green"]'Expand Column groups, Collapse Row groups – need to hide lower table[/COLOR]
    [COLOR="Red"].Outline.ShowLevels RowLevels:=1, ColumnLevels:=2[/COLOR]
    
    LastRow = Worksheets("4050CC30001").Cells(Rows.Count, "B").End(xlUp).Row
    .Range(.Cells(1, 2), .Cells(LastRow, 13)).Select
 End With
 
 End Sub



This is an example of how you can loop through an array of worksheets...
Code:
        For Each ws In SourceWB.Sheets(Array("4050CC30001", "301AA1234", "50BB9999", "65961LL3201"))
 
            If ws.Visible <> xlSheetHidden Then
 
Upvote 0
I simplified the bigger Macro for testing of just this range setting function.
I can't get it to work within the parameters of the n

Sub testing456() only works for contiguous data using Region like in data filters.

Sub testing123() below works (outside bigger Macro)

Both of your choices run but stop at your commands. I wrote the error msgs as text in the code. Note: Changed starting column, row bc I was pulling from a different set of reports with a contiguous data table.
Code:
             'Set rngSrc = ws.Range("A21:M" & LastRow)    'doesn't work Reason 1
   'Reason1 - Run-Time 1004:
   'Method 'Range' of object '_Worksheet' failed
                'Set rngSrc = ws.Range(ws.Cells(21, 1), ws.Cells(LastRow, 13)) 'doesn't work Reason 2
   'Reason2 - Run-Time 1004:
   'Application-defined or object-defined error

Bigger, modified testing code:
Code:
Option Explicit
Sub testing456()
Dim MasterWB As Workbook
Dim SourceWB As Workbook
Dim rngSrc As Range
Dim rngDst As Range
Dim ws As Worksheet
Dim LastRow As Long
Set MasterWB = Workbooks("Incoming-draft.xlsm")
Set SourceWB = Workbooks("Source Report.xlsx")
        For Each ws In SourceWB.Worksheets
            If ws.Name Like "4050CC30001" Then
                'copy
                LastRow = LastRow = ws.Cells(Rows.Count, "B").End(xlUp).Row
                'Set rngSrc = ws.Range("A21:M" & LastRow)    'doesn't work Reason 1
   'Reason1 - Run-Time 1004:
   'Method 'Range' of object '_Worksheet' failed
                'Set rngSrc = ws.Range(ws.Cells(21, 1), ws.Cells(LastRow, 13)) 'doesn't work Reason 2
   'Reason2 - Run-Time 1004:
   'Application-defined or object-defined error

                Set rngSrc = ws.Range("A21").CurrentRegion.Offset(0, 0) 'works for contiguous data
                rngSrc.SpecialCells(xlCellTypeVisible).Copy
            End If
        Next ws
End Sub
This Code does work:
Code:
Sub testing123()
 'this works on its own but not inside the above macro
    Dim LastRow As Long
 
    With Worksheets("4050CC30001")
          LastRow = Worksheets("4050CC30001").Cells(Rows.Count, "B").End(xlUp).Row
         .Range(Cells(21, 1), Cells(LastRow, 13)).Select
     End With
End Sub
 
Upvote 0
Alphafrog: The array works with the Set range command:
Code:
Set rngSrc = ws.Range("A21").CurrentRegion.Offset(0, 0)
Thank you - Rowland
 
Upvote 0
I had a typo, that's why it didn't work. I had
Code:
"LastRow=LastRow"
I added a message box to my test to see what my LastRow number and realized it wasn't working.
 
Upvote 0
Alphaforg:

It works! Thanks.

My data is on the 2nd table, Table 1 starts in cell A5 with blank cells under it until it reaches the beginning of Table 2 with my data. Now if the Report lines change, it doesn't matter.

Code:
Sub testing101112()
Dim MasterWB As Workbook
Dim SourceWB As Workbook
Dim rngSrc As Range
Dim rngDst As Range
Dim ws As Worksheet
Dim LastRow As Long
Dim FirstRow As Long
Set MasterWB = Workbooks("Incoming-draft.xlsm")
Set SourceWB = Workbooks("Source Report.xlsx")
        For Each ws In SourceWB.Sheets(Array("4050CC30001", "301AA1234"))
            If ws.Visible <> xlSheetHidden Then
                'copy
                LastRow = ws.Cells(Rows.Count, "B").End(xlUp).Row
                FirstRow = ws.Range("A5").End(xlDown).Row
                                          
                'Set rngSrc = ws.Range("A21").CurrentRegion.Offset(0, 0) 'this work
                'Works for contiguous data
                
                'Set rngSrc = ws.Range("A21:M" & LastRow) 'this works
                
                Set rngSrc = ws.Range("A" & FirstRow & ":M" & LastRow) 'this works
                
                'MsgBox FirstRow = to test if it works
                
                rngSrc.SpecialCells(xlCellTypeVisible).Copy
            End If
        Next ws
End Sub
Now, I have options.

Thanks, Rowland
 
Upvote 0
Using Defined Sheet Names between workbooks within For Each command

How do I use defined sheet names throughout my Macro? Do I need full paths? For example, I don't know how to change the following:
Code:
'paste<?xml:namespace prefix = o ns = "urn:schemas-microsoft-com:office:office" /><o:p></o:p>
                Set rngDst = MasterWB.Sheets("Master-Incoming").Range("B" & Rows.Count).End(xlUp).Offset(1, -1)<o:p></o:p>
So that I use a defined term from up top:
Code:
Set Unformatted = Worksheets("Master-Incoming")<o:p></o:p>
sfullpathUnf = "[" & Unformatted.Parent.Name & "]" & Unformatted.Name<o:p></o:p>

The full code below works, now want to use these defined terms:
Code:
Sub Pull_From_Source()<o:p></o:p>
'Uses file browser for source workbook, array for tab choices, find row options<o:p></o:p>
<o:p> </o:p>
Dim MasterWB As Workbook<o:p></o:p>
Dim SourceWB As Workbook<o:p></o:p>
<o:p> </o:p>
Dim Unformatted As Worksheet<o:p></o:p>
Dim sfullpathUnf As String<o:p></o:p>
<o:p> </o:p>
Dim rngSrc As Range<o:p></o:p>
Dim rngDst As Range<o:p></o:p>
Dim ccDst As Range<o:p></o:p>
Dim ws As Worksheet<o:p></o:p>
Dim varFileName As Variant<o:p></o:p>
Dim LastRow As Long<o:p></o:p>
Dim FirstRow As Long<o:p></o:p>
<o:p> </o:p>
Set MasterWB = ThisWorkbook<o:p></o:p>
Set Unformatted = Worksheets("Master-Incoming")<o:p></o:p>
sfullpathUnf = "[" & Unformatted.Parent.Name & "]" & Unformatted.Name<o:p></o:p>
<o:p> </o:p>
 ''''''''''Clear MasterWB'''''''''''''''''''''''''''''''''''''''''''''''''''''<o:p></o:p>
    MasterWB.Activate<o:p></o:p>
    Unformatted.Activate<o:p></o:p>
       Cells.Select<o:p></o:p>
        Selection.Clear<o:p></o:p>
    Range("a1").Select<o:p></o:p>
 '''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''<o:p></o:p>
    varFileName = Application.GetOpenFilename(, , "Please select source workbook:")<o:p></o:p>
<o:p> </o:p>
    If TypeName(varFileName) = "String" Then<o:p></o:p>
 <o:p></o:p>
       Set SourceWB = Workbooks.Open(Filename:=varFileName, UpdateLinks:=0)<o:p></o:p>
 <o:p></o:p>
       For Each ws In SourceWB.Sheets(Array("4050CC30001", "301AA1234"))<o:p></o:p>
            If ws.Visible <> xlSheetHidden Then<o:p></o:p>
                                 <o:p></o:p>
                'copy<o:p></o:p>
                LastRow = ws.Cells(Rows.Count, "B").End(xlUp).Row<o:p></o:p>
                FirstRow = ws.Range("A5").End(xlDown).Row<o:p></o:p>
                <o:p></o:p>
              Set rngSrc = ws.Range("A" & FirstRow).CurrentRegion.Offset(0, 0) 'this works<o:p></o:p>
                'Set rngSrc = ws.Range("A21").CurrentRegion.Offset(0, 0)'this works<o:p></o:p>
                'Set rngSrc = ws.Range("A" & FirstRow & ":M" & LastRow) 'this works<o:p></o:p>
                'Set rngSrc = ws.Range("A21:M" & LastRow)               'this works<o:p></o:p>
                'Set rngSrc = ws.Range(ws.Cells(21, 1), ws.Cells(LastRow, 13))'Didn't try<o:p></o:p>
                <o:p></o:p>
                'MsgBox FirstRow 'Test if it works<o:p></o:p>
 <o:p></o:p>
                'paste<o:p></o:p>
                Set rngDst = MasterWB.Sheets("Master-Incoming").Range("B" & Rows.Count).End(xlUp).Offset(1, -1)<o:p></o:p>
 <o:p></o:p>
                rngSrc.SpecialCells(xlCellTypeVisible).Copy<o:p></o:p>
 <o:p></o:p>
                rngDst.PasteSpecial Paste:=xlPasteValues<o:p></o:p>
                rngDst.PasteSpecial Paste:=xlPasteFormats<o:p></o:p>
                Application.CutCopyMode = False<o:p></o:p>
                <o:p></o:p>
                Set ccDst = MasterWB.Sheets("Master-Incoming").Range("A" & Rows.Count).End(xlUp).Offset(0)<o:p></o:p>
                ccDst.Formula = ws.Name<o:p></o:p>
                <o:p></o:p>
            End If<o:p></o:p>
 <o:p></o:p>
        Next ws<o:p></o:p>
 <o:p></o:p>
        SourceWB.Close False<o:p></o:p>
 <o:p></o:p>
        'MsgBox "Copied all data from source workbook"<o:p></o:p>
    Else<o:p></o:p>
        'MsgBox "No file selected"<o:p></o:p>
    End If<o:p></o:p>
<o:p> </o:p>
    Application.Goto MasterWB.Worksheets("Master-Incoming").Range("A1"), True<o:p></o:p>
    Selection.EntireRow.Delete<o:p></o:p>
End Sub
Thank you, Rowland
 
Upvote 0
Nevermind, it was easier than I thought - Thanks, Rowland:

Code:
Set rngDst = Unformatted.Range("B" & Rows.Count).End(xlUp).Offset(1, -1)
 
Upvote 0

Forum statistics

Threads
1,223,236
Messages
6,170,912
Members
452,366
Latest member
TePunaBloke

We've detected that you are using an adblocker.

We have a great community of people providing Excel help here, but the hosting costs are enormous. You can help keep this site running by allowing ads on MrExcel.com.
Allow Ads at MrExcel

Which adblocker are you using?

Disable AdBlock

Follow these easy steps to disable AdBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the icon in the browser’s toolbar.
2)Click on the "Pause on this site" option.
Go back

Disable AdBlock Plus

Follow these easy steps to disable AdBlock Plus

1)Click on the icon in the browser’s toolbar.
2)Click on the toggle to disable it for "mrexcel.com".
Go back

Disable uBlock Origin

Follow these easy steps to disable uBlock Origin

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back

Disable uBlock

Follow these easy steps to disable uBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back
Back
Top