简体   繁体   中英

Excel VBA - Repeating Cell Range in different sheet

I am trying to copy a range of cells that contain names, such as:

UBBR1
UBBR2
UESR1
UESR2
UDCR1
UDCR2
SBBR1
SBBR2
SESR1
SPDCR1
SPDCR2
SADCR1
GCCS-M DBM
SADCR2
SPDCR3
SCIBBR1
SCIDCR1
SVTCR1 

The range of those cells is stored in a variant called mapping listed below.Into another sheet. The number of times these names get repeated depends on the number of rows that are in another sheet. Each name above has a unit number that is in its same row, I store in another variant called ddg. The unit numbers stored in ddg refer to the names of different sheets in this workbook where the tables of data I am using are stored. For example, 2 below refers to "Unit #2" which is a table that has 38 rows, so UBBR1(Above) would need to be repeated 38 times.

ddg:

2
2
61
64
11
14
4
4
61
16
14
16
42
18
19
9
20
51

Code:

ddg = ws.Range("E4:E21").Value
mapping = ws.Range("B4:B21").Value

For Each k In ddg
        m = "Unit #" & k
        lastN = Sheets("Test").Range("B50000").End(xlUp).Row + 1

    For Each i In mapping


       N = Cells(Sheets(m).Rows.count, 1).End(xlUp).Row

        For j = 1 To N


        Sheets("Test").Range("B" & lastN).Value = i

        Next j


    Next i

Next k

Where i is a variant and mapping is also a variant that contains the range of the cells that contain the names. N is a long that gets row count of the sheet for the repetition. I am not sure what I am doing wrong but the loop does not repeat the values instead it loops through everything in mapping, leaves that in the cell and does the same all the way down. Any help would be greatly appreciated.

Untested, but something like this should work

Sub Tester()

    Dim ddg, mapping, k As Long,  N As Long
    Dim unitNum, nm

    '...
    '...

    ddg = ws.Range("E4:E21").Value
    mapping = ws.Range("B4:B21").Value

    For k = 1 To UBound(ddg, 1)

        unitNum = ddg(k, 1)
        nm = mapping(k, 1)

        With Sheets("Unit #" & unitNum)
            N = .Cells(.Rows.Count, 1).End(xlUp).Row
        End With

        Debug.Print N & " rows for Unit# " & unitNum & " (" & nm & ")" '<<<

        Sheets("Test").Range("B50000").End(xlUp).Offset(1, 0) _
                                      .Resize(N, 1).Value = nm

    Next k


End Sub

You only need one loop, and you can write all the values in one shot.

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