Below the code I wrote. It works in debug mode, but crashed when I tried to run the macro. I guess it relates to selection command, but I couldn't figure out the exact issue.
Can someone help? Thanks!
Sub copyemployeeTCdata()
Dim e_row, e_row2, e_row3 As Integer
Dim data_sh As Worksheet
Set data_sh = ThisWorkbook.Sheets("merg")
Dim setting_sh As Worksheet
Set setting_sh = ThisWorkbook.Sheets("chart")
Set pt = setting_sh.PivotTables("PivotTable1")
e_row = pt.TableRange1.Rows.Count - 1
setting_sh.Range("R:R").Clear
setting_sh.Range("S:S").Clear
e_row2 = 0
For i = 1 To e_row
data_sh.Activate
On Error Resume Next
data_sh.ShowAllData
data_sh.UsedRange.AutoFilter 22, setting_sh.Range("A" & 57 + i).Value
Set CopyTable = data_sh.Range("AE:AE")
Set CopyTable = CopyTable.Resize(CopyTable.Rows.Count - 1)
Set CopyTable = CopyTable.Offset(1)
CopyTable.Copy
'CopyTable.Select
setting_sh.Activate
'calculate last row -erow2 in column S
e_row2 = setting_sh.Cells(Rows.Count, 19).End(xlUp).Row
If e_row2 < 56 Then
setting_sh.Cells(57, 19).Select
ActiveSheet.Paste
e_row3 = setting_sh.Cells(Rows.Count, 19).End(xlUp).Row
setting_sh.Range(Cells(57, 18), Cells(e_row3, 18)).Value = i
Else
setting_sh.Cells(e_row2 + 1, 19).Select
Selection.PasteSpecial transpose:=False
e_row3 = setting_sh.Cells(Rows.Count, 19).End(xlUp).Row
setting_sh.Range(Cells(e_row2 + 1, 18), Cells(e_row3, 18)).Value = i
End If
Next i
End Sub
Thanks!