Excel Macro to duplicate info based on value in another cell

Closed
patrick.gilchrist Posts 1 Registration date Friday April 28, 2023 Status Member Last seen April 28, 2023 - Apr 28, 2023 at 11:41 AM
Aron_7608 Posts 3 Registration date Tuesday December 15, 2020 Status Member Last seen May 15, 2023 - May 15, 2023 at 02:31 AM

I am creating a work book that has a range of cells (C6:E34) that are considered one "Location", and another cell (D5) to input the number of locations in the sheet. What I'm looking to do is set up a macro to automatically duplicate that range of cells once the D5 cell has been changed, but duplicate it the number of times equal to the value in cell D5. Is this something that's possible?

Related:

1 response

Aron_7608 Posts 3 Registration date Tuesday December 15, 2020 Status Member Last seen May 15, 2023
May 15, 2023 at 02:31 AM

Hey patrick,

Yes, it is possible to create a macro in Excel that duplicates a range of cells based on the value in a specific cell. Here's an example VBA code that can do it-

Sub DuplicateCells()
    Dim rngSource As Range
    Dim rngDestination As Range
    Dim count As Long
    Dim i As Long
    
    ' Set the source range to be duplicated
    Set rngSource = Range("C6:E34")
    
    ' Get the number of locations from cell D5
    count = Range("D5").Value
    
    ' Clear any existing duplicated ranges
    Range("C6:E34").ClearContents
    
    ' Loop through the count and duplicate the range
    For i = 1 To count
        ' Calculate the destination range for each duplication
        Set rngDestination = rngSource.Offset((i - 1) * rngSource.Rows.Count, 0)
        
        ' Copy and paste values from the source to the destination range
        rngSource.Copy
        rngDestination.PasteSpecial Paste:=xlPasteValues
    Next i
    
    ' Clear the clipboard
    Application.CutCopyMode = False
End Sub

In this code, the DuplicateCells subroutine is triggered when the value in cell D5 is changed. It clears any existing duplicated ranges and then duplicates the range C6:E34 based on the count specified in cell D5. The duplicated ranges are pasted as values to avoid any formula dependencies.

You can assign this macro to a button or run it manually whenever you want to duplicate the range.

I hope this helps. :)

Best Regards.

0