Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
617 views
in Technique[技术] by (71.8m points)

excel - VBA, Why does pasting my array only paste one cell

I get all my values into an array and I want to paste it over to another workbook. How come this isnt working? It is only pasting the cell A2 of destination workbook. Do I have to select the full range to paste it?

According to the answer here, the answer just pastes to one cell. Save range to variable

Dim src As Variant
Application.ScreenUpdating = False
Application.DisplayAlerts = False

'Open CM comm file
Set MainDataCM = Workbooks.Open(Sheets("Input").Range("B3") & Sheets("Input").Range("B6"))

'Copy main data tab to EPM file workbook
With Sheets("Main Data")
lastrow = Sheets("Main Data").Range("A" & .Rows.Count).End(xlUp).Row
src = Sheets("Main Data").Range("A2:P" & lastrow).Value
End With
MainDataCM.Close SaveChanges:=False

'Paste into active workbook
Set MainDataCIB = Workbooks.Open(ThisWorkbook.Sheets("Input").Range("B3") & Sheets("Input").Range("B9"))
With Sheets("Main Data")
lastrow = Sheets("Main Data").Range("A" & .Rows.Count).End(xlUp).Row
Sheets("Main Data").Range("A2:P" & lastrow).ClearContents
MainDataCIB.Sheets("Main Data").Range("A2").Value = src
End With

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

In order to output your array to a range, you need to give it the correct dimensions to output. The best way I find to do this is using the .Resize property of the specified range. See code below.

MainDataCIB.Sheets("Main Data").Range("A2").Resize(UBound(src,1), UBound(src,2)).Value = src

This approach will ensure that you are giving accurate dimensions to your output.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...