简体   繁体   中英

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!

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

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM