简体   繁体   中英

Overwriting & Resizing Arrays in Excel VBA

See end for an edit in response to PatricK's comment.

Apologies if this is a basic question, but I have been looking around here and other sites and cannot find the answer.

This is my first foray into VBA arrays (I'm new to VBA in general) and I'm struggling with some syntax. I am trying to read some data (part of a single column) from a worksheet into an array, do some processing on it, write it to a different sheet and then overwrite the array with some more data read from the first sheet. One key point is that the number of data points read per iteration will vary (eg 4 data points on the first loop, 3 on the second perhaps...) and so the array size should change too.

My attempt at the code works for the first iteration, but it does not seem to pick up the data on the second loop, instead leaving the array blank. Here's my code (sorry if this doesn't format properly, I only currently have internet access via my phone!):

Looping...

Dim DataSubSet

With ActiveWorkbook.Worksheets("Sheet1").Range("A" & CStr(I) & ":A" & CStr(io))
ReDim DataSubSet(1 To .Rows.Count, 1 To .Columns.Count)
DataSubSet = .Range ("A" & CStr(I) & ":A" & CStr(io))
End With

**Do processing** 

End loop

Here i and io are variables that determine the cells that I'm interested in; they each change with the overarching loop.

As I mentioned, this works for the first iteration only. Any pointers on where I've gone wrong would be appreciated!

Thanks in advance, Sam

-----------------------------------------------------------------------------------

PatricK, for further clarification, here's a quick routine that I knocked up to illustrate your point.

** formatting check failed (still writing on phone) so wouldn't let me post. Here's a dropbox link to the code in a text file:

https://db.tt/E0btoI5f

One possible reason it worked once may be because the "Do processing" codes Activated another workbook. Also not sure why you use 2D array to store 1D array values.

But please try:

Dim oWB as Workbook
' Loop Start

Set oWB = ActiveWorkbook
'Or Set oWB = Workbooks("<workbook name you are trying to get the data from>")    
With oWB.Worksheets("Sheet1").Range("A" & i & ":A" & io)
    ReDim DataSubSet(1 To .Rows.Count, 1 To .Columns.Count)
    DataSubSet = .Value
End With

' Do Processing and finish loop above this line
Set oWB = Nothing

Test data in Sheet1 :

测试数据

Watching the variable DataSubSet (I have set i = 3 and io = 10 ):

监视输出

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