Hi All,
Today a colleague asked me to help write a macro to copy and paste specific data. the simple rule was that each worksheet in the "target" workbook (where data was to be pasted, had a worksheet with a data varaible name e.g. "N95", "N08" etc which were codes.
These worksheet names i.e. codes, were the key variables used to filter the required data and then copying it and pasting it in the original worksheet.
the following macro works, quite quickly only 2-5 seconds for the entire workbook, but I;m sure it could be coded better:
[vba]Option Explicit
Sub test()
Call copyPasteV("C:\KeySourcedata_Workbook.xls", "Worksheet_keydata_tocopy", "data_AAL")
End Sub
Sub copyPasteV(strSourcewbkname As String, strSourcewkshtname As String, strdatarng As String)
Dim wbksourcedata As Excel.Workbook
Dim wksht As Excel.Worksheet
Dim starttime As Double
starttime = Timer
Application.ScreenUpdating = False
Set wbksourcedata = Workbooks.Open(strSourcewbkname, UpdateLinks:=0)
On Error Resume Next
For Each wksht In ThisWorkbook.Worksheets
wbksourcedata.Activate
Worksheets(strSourcewkshtname).Activate
' Filter the named range in the relevant worksheet that we will open
wbksourcedata.Worksheets(strSourcewkshtname).Range(strdatarng).AutoFilter
Range("B2").Select
Range("B2").Select
Selection.AutoFilter Field:=2, Criteria1:=wksht.Name
Range("A2").Select
Range(Selection, Selection.End(xlToRight)).Select
Range(Selection, Selection.End(xlDown)).Select
Selection.Offset(1, 0).Copy
ThisWorkbook.Activate
Worksheets(wksht.Name).Select
Range("B5").Select
Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
:=False, Transpose:=False
Selection.PasteSpecial Paste:=xlPasteFormats, Operation:=xlNone, _
SkipBlanks:=False, Transpose:=False
wbksourcedata.Activate
Worksheets(2).Activate
Application.CutCopyMode = False
Range("A2").Select
wbksourcedata.Worksheets(strSourcewkshtname).Range(strdatarng).AutoFilter
Range("A2").Select
Next wksht
On Error GoTo 0
Set wbksourcedata = Nothing
Application.ScreenUpdating = True
MsgBox "macro took " & (Timer - starttime) & " seconds to finish"
End Sub[/vba]
Any ideas how to improve the syntax etc to only keep the essential elements VBAXers?
Also what sort of key error-handling could I employ going forward?
Any feedback and suggestions appreciated.