Hi, I am new to VBA Macros and I have completed my first VBA based on my work requirement. It works satisfactorily.
But I just want to know how to streamline my coding and remove any unnecessary code. Thanks.
Coding Sample:
>>> use code - tags <<<
But I just want to know how to streamline my coding and remove any unnecessary code. Thanks.
Coding Sample:
>>> use code - tags <<<
Code:
Sub Assign_Workbook()
Dim ws1 As Worksheet, ws2 As Worksheet, last_row As Long
Dim ws3 As Worksheet, ws4 As Worksheet, ws5 As Worksheet, ws6 As Worksheet
Set ws1 = ThisWorkbook.Sheets("Source")
Set ws2 = ThisWorkbook.Sheets("A")
Set ws3 = ThisWorkbook.Sheets("B")
Set ws4 = ThisWorkbook.Sheets("C")
Set ws5 = ThisWorkbook.Sheets("D")
Set ws6 = ThisWorkbook.Sheets("E")
'define last rows
last_row2 = ws2.Range("A" & Rows.Count).End(xlUp).Row
last_row3 = ws3.Range("A" & Rows.Count).End(xlUp).Row
last_row4 = ws4.Range("A" & Rows.Count).End(xlUp).Row
last_row5 = ws5.Range("A" & Rows.Count).End(xlUp).Row
last_row6 = ws6.Range("A" & Rows.Count).End(xlUp).Row
'Clear sheet
ws2.Cells.Clear
ws3.Cells.Clear
ws4.Cells.Clear
ws5.Cells.Clear
ws6.Cells.Clear
'Set first row data
ws1.Range("A1:K1").Copy ws2.Range("A1:K1")
ws1.Range("A1:K1").Copy ws3.Range("A1:K1")
ws1.Range("A1:K1").Copy ws4.Range("A1:K1")
ws1.Range("A1:K1").Copy ws5.Range("A1:K1")
ws1.Range("A1:K1").Copy ws6.Range("A1:K1")
'Copy rows
For j = 1 To 500
last_row2 = ws2.Range("A" & Rows.Count).End(xlUp).Row
last_row3 = ws3.Range("A" & Rows.Count).End(xlUp).Row
last_row4 = ws4.Range("A" & Rows.Count).End(xlUp).Row
last_row5 = ws5.Range("A" & Rows.Count).End(xlUp).Row
last_row6 = ws6.Range("A" & Rows.Count).End(xlUp).Row
'If A = Y
If (ws1.Cells(j + 1, 13).Value = "Y") Then
ws1.Range("A" & j + 1 & ":K" & j + 1).Copy ws2.Range("A" & last_row2 + 1)
End If
'If B = Y
If (ws1.Cells(j + 1, 14).Value = "Y") Then
ws1.Range("A" & j + 1 & ":K" & j + 1).Copy ws3.Range("A" & last_row3 + 1)
End If
'If C = Y
If (ws1.Cells(j + 1, 15).Value = "Y") Then
ws1.Range("A" & j + 1 & ":K" & j + 1).Copy ws4.Range("A" & last_row4 + 1)
End If
'If D = Y
If (ws1.Cells(j + 1, 16).Value = "Y") Then
ws1.Range("A" & j + 1 & ":K" & j + 1).Copy ws5.Range("A" & last_row5 + 1)
End If
'If E = Y
If (ws1.Cells(j + 1, 17).Value = "Y") Then
ws1.Range("A" & j + 1 & ":K" & j + 1).Copy ws6.Range("A" & last_row6 + 1)
End If
Next j
End Sub
Last edited by a moderator: