In another thread I'd been given some help to design a macro that copies and pastes a range from one workbook to another.
In brief, the macro opens one file at a time from a list called rFiles, and copies a specific range from the master sheet into the new sheet, and then re-sorts the sheet and closes it; opens the next and then repeats the process. Full code is below.
My questions are:
1) the line
rDest.Sort key1:=rDest(1, 2), Header:=xlYes
works, but the line
rDest.Sort key1:=rDest(1, 2), key2:=rDest.Cells(1, 3), key3:=rDest.Cells(1, 4), key4:=rDest.Cells(1, 6), Header:=xlYes
does not.
There are definitely at least 6 columns in the range! Any idea what the problem is?
2) how can I adapt the macro to "paste values" rather than just pasting?
Full code is here:
Sub FebruaryAddNewPupils()
Application.ScreenUpdating = True
Application.DisplayAlerts = False
Dim Subfolder As String
Dim SubfolderSubjNom As String
Dim SubjFile As String
Dim wbk As Workbook
Dim rFiles As Range, rFree As Range
Dim rData As Range, rDest As Range
Dim iLR As Integer
Dim ws As Worksheet
Sheets("Staff").Select
Subfolder = ActiveSheet.Range("G1").Value
SubfolderSubjNom = Subfolder & "SubjectNominations\"
Set rFiles = ThisWorkbook.Sheets("Staff").Range("B1:B11")
Set rData = ThisWorkbook.Sheets("Pupils").Range("H10:M12")
For Each rFree In rFiles
SubjFile = SubfolderSubjNom & rFree.Value & ".xlsm"
Set wbk = Workbooks.Open(SubjFile)
Set ws = wbk.Sheets("Nominations")
If rFree.Value <> "" Then
With ws
.Unprotect
iLR = .Range("A" & .UsedRange.Rows.Count).Row + 1
rData.Copy Destination:=.Range("A" & iLR)
'start re-sorting
'reset last row in destination workbook
iLR = .Range("A" & .Rows.Count).End(xlUp).Row
'define range to be sorted
Set rDest = .Range("A5:W" & iLR)
'sort by columns B,C,D & F relative to top left cell of defined range
rDest.Sort key1:=rDest(1, 2), key2:=rDest.Cells(1, 3), key3:=rDest.Cells(1, 4), key4:=rDest.Cells(1, 6), Header:=xlYes
'end re-sorting
.Range("A2").Select
.Protect DrawingObjects:=True, Contents:=True, Scenarios:=True, AllowFiltering:=True
End With
wbk.Save
wbk.Close
End If
Next rFree
End Sub
Bookmarks