简体   繁体   中英

VBA how to pass a string array to range

The usual issue is to pass range to array, but this time I need to do the opposite. I want to pass various size string array to a range. BR Michał

To set the value of a range from an array, we must first determine the size of that range dependent of the arrays size. For this we can use the bounds ( LBound and UBound ) of the array.

Then, if the array fits into the range, we can simply do range.value = arr .

Example:

Sub test()

 Cells.ClearContents

 ' one dimensional array; base 0
 aSArr = Array("This", "is", "an", "array", "of", "strings")

 Set r1 = Range("C3").Resize(1, 1 + UBound(aSArr))
 r1.Value = aSArr

 Set r2 = Range("C5").Resize(1 + UBound(aSArr), 1)
 r2.Value = Application.Transpose(aSArr)

 ' two dimensional array; base 1
 aSArr = [{"This", "is", "an"; "array", "of", "strings"}]

 Set r3 = Range("E6").Resize(UBound(aSArr, 1), UBound(aSArr, 2))
 r3.Value = aSArr


End Sub

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