简体   繁体   中英

VBA - How to triplet each cell in the array

I'm trying to get all the unique values in column A and insert them to the array: "uniqueNameList".

after that, I want to triplet each cell in my array.

For example:

column A:

A
One
Two
Three
Three
One
Two

the "uniqueNameList" array will be:

("One", "Two", "Three")

And after triplet it will be:

("One","One","One", "Two", "Two", "Two", "Three", "Three", "Three")

I've tried this and I do get the "uniqueNameList" array as expected. but I didn't manage to triplet the Items. This is my code:

Sub test()

Dim myList As Variant, uniqueNameList As Variant, arr3 As Variant
Dim itemCount As Long
myList = shTest.Range("A1").CurrentRegion
uniqueNameList = WorksheetFunction.Unique(myList)
itemCount = WorksheetFunction.CountA(uniqueNameList)
ReDim arr3(1 To (itemCount * 3))
Dim i As Long, j As Long

For i = 1 To UBound(uniqueNameList)
    
    arr3(i) = uniqueNameList(i, 1)
    arr3(i + 1) = uniqueNameList(i, 1)
    arr3(i + 2) = uniqueNameList(i, 1)
    
Next i


End Sub

Thanks in advance!

You need to multiply the index for arr3 by 3. For the first iteration (i=1), you want to write into index 1, 2, 3, for the second interation (i=2) into 4, 5, 6 and so on.

For i = 1 To UBound(uniqueNameList)
    arr3(i * 3 - 2) = uniqueNameList(i, 1)
    arr3(i * 3 - 1) = uniqueNameList(i, 1)
    arr3(i * 3 - 0) = uniqueNameList(i, 1)
Next i

if your uniquenamelist array starts from 0 and arr3 starts from 1 then try this.

`For i = LBound(uniqueNameList) To UBound(uniqueNameList)
    
    arr3((3 * i) + 1) = uniqueNameList(i)
    arr3((3 * i) + 2) = uniqueNameList(i)
    arr3((3 * i) + 3) = uniqueNameList(i)
    
Next i

`

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