હિમાંશુ પરભુભાઇ મિસ્ત્રી | Himanshu Mistry

જૂન 5, 2008

MS Excel macro recording with relative reference

Filed under: Uncategorized — Himanshubhai Mistry @ 9:06 પી એમ(pm)

We use MS Excel very much at our work.

Some time we need to do some repetitive task, for which we record a macro and run it as many time as we need to do so.

Generally the macro recording is done with relative reference set to “OFF”

because of that we might feel our macro is not working.

We need to record the macro with relative reference. For that I found wonderful tutorial (with screen shots) on this website: http://www.mrexcel.com/tip077.shtml

Here is an example I recently recorded/modified and used for my work:

I had two excel documents.
I had to copy value from first document (doc1.xls>>sheet1>>row1>>column1)
and search in second document.
If it is found (say doc2.xls>>sheet1>>row15>>column1), then
I had to copy corresponding value given in 3rd column in same row from found value,
(say doc2.xls>>sheet1>>row15>>column3),
and then paste in the column next column in doc1
(doc1.xls>>sheet1>>row1>>column2)

I had to repeat this process for 107 items in doc1.xls
I just recorded a macro.. modified for my requirements. assign it to a button on custom toolbar. and simply clicked 107 times. I got corresponding values from doc2.xls for 107 items in my doc1.xls
Life became easy.

Private sub Macro1()
Dim sComponent As String
    Selection.Copy
    sComponent = Selection.Text
    Windows("Copy of OGL Changes_Review.xls").Activate
    Range("D1").Select
    Cells.Find(What:=sComponent, After:=ActiveCell, LookIn:=xlFormulas, LookAt _
        :=xlPart, SearchOrder:=xlByRows, SearchDirection:=xlNext, MatchCase:= _
        False, SearchFormat:=False).Activate
    ActiveCell.Offset(0, 2).Range("A1").Select
    Application.CutCopyMode = False
    Selection.Copy
    Windows("work document.xls").Activate
    ActiveCell.Offset(0, 1).Range("A1").Select
    ActiveSheet.Paste
    ActiveSheet.Paste
    Application.CutCopyMode = False
    ActiveCell.Offset(1, -1).Range("A1").Select
End Sub
 

Advertisements

Create a free website or blog at WordPress.com.