This is just to see how we can improve Mertinc's code to follow best practices with some minor improvements.
This is expressly not to blame anyone but good for learning purpose and seeing the differences.
Option Explicit
Sub TransformData()
Dim lastRowScr As Long, lastRowDest As Long
Dim numCols As Long
Dim wsSrc As Worksheet, wsDest As Worksheet
Set wsSrc = ThisWorkbook.Worksheets("Sheet1") '* worksheet with source data
Set wsDest = ThisWorkbook.Worksheets("Sheet2") '* another worksheet to paste data
Application.ScreenUpdating = False
lastRowScr = wsSrc.Range("A" & wsSrc.Rows.Count).End(xlUp).Row '* determine last row in column A
Dim iRow As Long
iRow = 1
Do While iRow <= lastRowScr
With wsSrc.Range(wsSrc.Range("B" & iRow), wsSrc.Range("A" & iRow).End(xlToRight))
numCols = .Count
.Copy
End With
With wsDest
lastRowDest = .Range("B" & .Rows.Count).End(xlUp).Row
If IsEmpty(.Range("B" & lastRowDest)) Then lastRowDest = lastRowDest - 1 '* make sure that we start in row 1
.Range("B" & lastRowDest + 1).PasteSpecial Paste:=xlPasteAll, Operation:=xlNone, SkipBlanks:=False, Transpose:=True
.Range("A" & lastRowDest + 1).Resize(numCols, 1).Value = wsSrc.Range("A" & iRow).Value
End With
iRow = iRow + 1
Loop
Application.ScreenUpdating = True
End Sub
This procedure uses sheet1
as data source and inserts the transformed data into sheet2
.
Explanations
Here I try to explain the differences and show some further literature.
1. Always use descriptive variable and procedure/function naming
Using your username for naming procedures and variables
Sub mertinc()
Dim mert, inc As Long
is bad practice instead you should use descriptive names like
Sub TransformData()
Dim lastRowScr As Long, lastRowDest As Long
Dim numCols As Long
also every variable needs to be specified with a type. Dim mert, inc As Long
will leave mert
as variant and only declares inc
as long.
Much better readability for yourself and other persons and therefore probably less issues in your codes.
2. Always use long instead of integer
Never use integer unless you need to interop with an old API call that expects a 16 bit int. There is no advantage using integer instead of long.
3. Avoid using Select or Activate
Instead of using .Select
or .Activate
Range("a1048576").Select
lastRowScr = Selection.End(xlUp).Row
use a direct access
lastRowScr = Range("a1048576").End(xlUp).Row
Much faster and shorter code.
4. Also never assume the worksheet
Always use full qualified ranges
Set ws = ThisWorkbook.Worksheets("Sheet1")
lastRowScr = ws.Range("a1048576").End(xlUp).Row
Less issues. If another sheet was selected, this code still works.
5. Never use fixed row counts
Instead of fixed row counts
lastRowScr = ws.Range("a1048576").End(xlUp).Row
always detect the last row
lastRowScr = ws.Range("A" & ws.Rows.Count).End(xlUp).Row
Different Excel versions have different max. row counts. Therefore this code runs version independent.