chicharito14
New Member
- Joined
- Apr 16, 2021
- Messages
- 5
Hi VBA experts,
Could you help me to write a for loop of this code. The purpose of this vba code is search for sheets that matchs SheetName column in SourceFile, copy data until the last rows of entry in Columns Range of Source File to Destination File.
I can do it without a loop as the code below.
Could you help me to write a for loop of this code. The purpose of this vba code is search for sheets that matchs SheetName column in SourceFile, copy data until the last rows of entry in Columns Range of Source File to Destination File.
I can do it without a loop as the code below.
VBA Code:
Sub CopyPaste_ColumnsRange()
Dim SourceFile As String, DestinationFile As String
Dim SheetName1 As String, SheetName2 As String, SheetName3 As String
Dim ColumnRange1 As String, ColumnRange2 As String, ColumnRange3 As String
Dim LastRow1 As Long, LastRow2 As Long, LastRow3 As Long
Dim WS1S As Worksheet, WS2S As Worksheet, WS3S As Worksheet, WS1D As Worksheet, WS2D As Worksheet, WS3D As Worksheet
SourceFile = ActiveSheet.Range("C2")
DestinationFile = ActiveSheet.Range("D2")
SheetName1S = ActiveSheet.Range("A2")
SheetName1D = Left(SheetName1S, 6)
ColumnRange1 = ActiveSheet.Range("B2")
Set WS1S = Workbooks(SourceFile).Sheets(SheetName1S)
Set WS1D = Workbooks(DestinationFile).Sheets(SheetName1D)
LastRow1 = WS1S.Cells.Find("*", , xlValues, , xlRows, xlPrevious).Row
Intersect(WS1S.Rows("1:" & LastRow1), WS1S.Range(ColumnRange1)).Copy WS1D.Range("A1")
SheetName2S = ActiveSheet.Range("A3")
SheetName2D = Left(SheetName2S, 6)
ColumnRange2 = ActiveSheet.Range("B3")
Set WS2S = Workbooks(SourceFile).Sheets(SheetName2S)
Set WS2D = Workbooks(DestinationFile).Sheets(SheetName2D)
LastRow2 = WS2S.Cells.Find("*", , xlValues, , xlRows, xlPrevious).Row
Intersect(WS2S.Rows("1:" & LastRow2), WS2S.Range(ColumnRange2)).Copy WS2D.Range("A1")
SheetName3S = ActiveSheet.Range("A4")
SheetName3D = Left(SheetName3S, 6)
ColumnRange3 = ActiveSheet.Range("B4")
Set WS3S = Workbooks(SourceFile).Sheets(SheetName3S)
Set WS3D = Workbooks(DestinationFile).Sheets(SheetName3D)
LastRow3 = WS3S.Cells.Find("*", , xlValues, , xlRows, xlPrevious).Row
Intersect(WS3S.Rows("1:" & LastRow3), WS3S.Range(ColumnRange3)).Copy WS3D.Range("A1")
End Sub