SilverFish
SilverFish

Reputation: 1106

How to dynamically get Active cell address and find out range in EXCEL VBA macro

In a Excel Macro, I want to achieve this: In 'A' column there can be data in a number of rows. When user selects any Cell in 'A' col, and clicks a button, then 6 rows get inserted below selected row and data from the selected cell gets copied over to those 6 rows. I recorded a macro, and here is what I have:

Sub MacroTest()
'
' MacroTest Macro
'

    Rows("5:5").Select
    Selection.Insert Shift:=xlDown, CopyOrigin:=xlFormatFromLeftOrAbove
    Selection.Insert Shift:=xlDown, CopyOrigin:=xlFormatFromLeftOrAbove
    Selection.Insert Shift:=xlDown, CopyOrigin:=xlFormatFromLeftOrAbove
    Selection.Insert Shift:=xlDown, CopyOrigin:=xlFormatFromLeftOrAbove
    Selection.Insert Shift:=xlDown, CopyOrigin:=xlFormatFromLeftOrAbove
    Selection.Insert Shift:=xlDown, CopyOrigin:=xlFormatFromLeftOrAbove
    Range("A4").Select
    Selection.AutoFill Destination:=Range("A4:A10"), Type:=xlFillDefault
End Sub

What I would like to know is how to replace A4 with Active cell, and the range A4:A10 and Active cell address + 6. Please advise!

Upvotes: 2

Views: 4008

Answers (2)

Marcucciboy2
Marcucciboy2

Reputation: 3257

Here's my take on it. This way you can easily adjust the number of cells that you want to copy after the activecell if you change your mind, and it gets rid of that verbose code :)

Sub MacroTest()

    If ActiveCell.Column = 1 Then

        Dim numCopies As Long
        numCopies = 6

        Dim i As Long
        For i = 1 To numCopies
            Rows(ActiveCell.row + 1).Insert Shift:=xlDown, CopyOrigin:=xlFormatFromLeftOrAbove
        Next i

        ActiveCell.AutoFill Destination:=Range(ActiveCell, ActiveCell.Offset(numCopies, 0)), Type:=xlFillDefault

    End If

End Sub

Upvotes: 3

Vityata
Vityata

Reputation: 43593

Recording a macro is one of the best ways to start programming in , congrats. This is how to do the ActiveCell and the Offset():

Sub MacroTest()
    Rows("5:5").Select
    Selection.Insert Shift:=xlDown, CopyOrigin:=xlFormatFromLeftOrAbove
    Selection.Insert Shift:=xlDown, CopyOrigin:=xlFormatFromLeftOrAbove
    Selection.Insert Shift:=xlDown, CopyOrigin:=xlFormatFromLeftOrAbove
    Selection.Insert Shift:=xlDown, CopyOrigin:=xlFormatFromLeftOrAbove
    Selection.Insert Shift:=xlDown, CopyOrigin:=xlFormatFromLeftOrAbove
    Selection.Insert Shift:=xlDown, CopyOrigin:=xlFormatFromLeftOrAbove
    'Range("A4").Select
    ActiveCell.Select
    Selection.AutoFill Destination:=Range(ActiveCell, ActiveCell.Offset(6, 0)), Type:=xlFillDefault
End Sub

If you want to have the code improved a bit, consider putting it in https://codereview.stackexchange.com, some good ideas would pop up.

E.g., not using Selecti in Excel - How to avoid using Select in Excel VBA.

Upvotes: 2

Related Questions