How do I amend this to use a destination sheet in a different workbook?

Mr Denove

Active Member
Joined
Jun 8, 2007
Messages
446
Code:
Sub Test()  'Stewarts working code with all Columns named correctly and Source Sheets defined
    
    
    
    SG_MoveColumns ("Starts")
    SG_MoveColumns ("Leavers (incl SSMA Prog)")
    SG_MoveColumns ("In-training")
    SG_MoveColumns ("Achievements")

End Sub




Sub SG_MoveColumns(sSheetname As String)
    
    Dim srcWorkbook As Workbook
    Dim srcLastRow As Double
    Dim srcLastCol As Double
    Dim tgt As Worksheet
    Dim tgtLastRow As Double
    Dim dest As Range
    Dim i As Long
    Dim x As Long
    Dim sColLetter As String
    Dim stgtColLetter As String
    Dim bFoundCol As Boolean
    

    ' Switch screen updating back off
    Application.ScreenUpdating = False

    ' Create objects to use
    
    Set src = Worksheets(sSheetname)  ' use sheet name passed in to the
    srcLastRow = src.Cells(Rows.Count, 1).End(xlUp).Row
    srcLastCol = src.Cells(1, Columns.Count).End(xlToLeft).Column
    
    Set tgt = Worksheets("SheetX")
    tgtLastRow = tgt.Cells(Rows.Count, 1).End(xlUp).Row

    ' Selects the columns to be copied
    myColumns = Array("Assignment id", "Programme", "Creditor", "Framework id", "MA framework desc", "Input Dat", "Start date", "VQ reference", "VQ title", "First names", "Last name", "NI number", "Date of birth", "Gender", "Trainee district desc", "Company town", "Company postcode in", "Company postcode out", "Learning Provider on Contract", "Updated Programme", "Age Band", "Updated Employer", "MA Framework Band", "STATUS")
    ' Search the source worksheet to find the columns that the required field are in
    For i = 0 To UBound(myColumns)
    On Error Resume Next
            
            ' search the column headers - assume that held in row 1
            '   set the flag to NOT FOUND
            bFoundCol = False
            
            For x = 1 To srcLastCol
            On Error Resume Next
            
                If Trim(UCase(myColumns(i))) = Trim(UCase(src.Cells(1, x).Text)) Then
                    bfound = True
                    
                    ' convert the column number in to a column letter
                    sColLetter = Col_Letter(x)
                    
                    ' convert the array to the target column letter
                    stgtColLetter = Col_Letter(i + 1)
                    
                    ' copy of the column data
                    src.Range(sColLetter & "2:" & sColLetter & srcLastRow).Copy tgt.Range(stgtColLetter & tgtLastRow + 1)

                    Exit For
                End If
            
            Next x
    Next i
        
    'Tidy-up created objects
    Set src = Nothing
    Set tgt = Nothing
    
    ' Switch screen updating back on
    Application.ScreenUpdating = True
    
    MsgBox "Complete All Columns"

End Sub

Function Col_Letter(lngCol As Long) As String
    Dim vArr
    
    ' calculate the letter linked to the column
    vArr = Split(Cells(1, lngCol).Address(True, False), "$")
    
    ' return the letter
    Col_Letter = vArr(0)
End Function

The above code is using SheetX in the workbook where the source worksheets are located.
How do I use another workbook/worksheet that is not the same as the source workbook/sheet?
Thanks, in advance
 

Excel Facts

Create a Pivot Table on a Map
If your data has zip codes, postal codes, or city names, select the data and use Insert, 3D Map. (Found to right of chart icons).
Did you try?

Code:
Set tgt = Workbooks("NameOfOtherWorkbook").Worksheets("SheetX")

changing NameOfOtherWorkbook to suit? The target workbook must be open of course.
 
Upvote 0
Hi Andrew,

Thanks for replying.

The full code runs, copies and now pastes into the destination file I am wanting. Thank you.
However, after I click OK on the MsgBox i get Runtime error 9 Subscript out of range.
Code:
Set src = Worksheets(sSheetname)

Would I be on the right track thinking it has looped too far and needs to be told when / where to stop?
 
Upvote 0
If you don't qualify the Worksheets property with its Workbook, the ActiveWorkbook will be used. To use the Workbook that contains your VBA code:

Code:
Set src = ThisWorkbook.Worksheets(sSheetname)
 
Upvote 0
All sorted now Andrew and thanks for your help.

Just the minor issue of the MsgBox prompting 3 times
 
Upvote 0
It will be getting used by other members of the team so its more a visual aid for them so would like to keep it if I can make it appear only once and / or finish on the destination file.
 
Upvote 0
Move it here then:

Rich (BB code):
Sub Test()  'Stewarts working code with all Columns named correctly and Source Sheets defined
    SG_MoveColumns ("Starts")
    SG_MoveColumns ("Leavers (incl SSMA Prog)")
    SG_MoveColumns ("In-training")
    SG_MoveColumns ("Achievements")
    MsgBox "Complete All Columns"
End Sub
 
Upvote 0

Forum statistics

Threads
1,216,743
Messages
6,132,457
Members
449,729
Latest member
davelevnt

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