简体   繁体   中英

Pasting VBA Array into Excel Range

I know this question has been asked multiple times, but I am kinda stuck adopting the suggested solutions to my problem.

I have an array(0 to 4), that gets filled multiple times in a loop and should be pasted each time into a new line in excel.

Expected Output:

      A      |      B      |      C     |      D     |      E
1     X1     |      X2     |      X3    |      X4    |      X5

My code:

r i = 0 To iVal
Dim infoarr(0 To 4) As Variant
infoarr(0) = ws_src_agv.Cells(ref + i + 3, 2).Value 
infoarr(1) = ws_src_agv.Cells(ref + i + 4, 2).Value 
infoarr(2) = ws_src_agv.Cells(ref + i + 3, 1).Value 
infoarr(3) = ws_src_agv.Cells(ref + i + 3, 3).Value 
infoarr(4) = ws_src_agv.Cells(ref + i + 3, 7).Value 

lastR = ws_tgt_agv.Rows(Rows.Count).End(xlUp).Row

'First attempt:
ws_tgt_agv.Range(ws_tgt_agv.Cells(lastR + 1, 1), ws_tgt_agv.Cells(lastR + 1, 5)).Value = WorksheetFunction.Transpose(infoarr)

Output:

      A      |      B      |      C     |      D     |      E
1     X1     |      X1     |      X1    |      X1    |      X1

2nd attempt:

 ws_tgt_agv.Cells(lastR + 1, 1).Resize(UBound(infoarr, 1) + 1).Value = WorksheetFunction.Transpose(infoarr)

Ouput:

      A      |      B      |      C     |      D     |      E
1     X1     |             |            |            |      
2     X2
3     X3
4     X4
5     X5

if leaving the transpose argument at the end the same range gets filled with sloley X1.

Thanks for your help!

A 1-D array (both zero based and one based) is aligned like a single row with multiple columns. You don't need to transpose in order to put te array's values into the worksheet; you only need the correct size of target.

with ws_tgt_agv
  .Range(.Cells(lastR + 1, 1), .Cells(lastR + 1, 5)).Value = infoarr
end with

If you want to put the array's values into a single column of multiple rows then you need to transpose.

with ws_tgt_agv
  .Range(.Cells(lastR + 1, 1), .Cells(lastR + 6, 1)).Value = Application.Transpose(infoarr)
end with

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