VBA - Extracting data from excel to a dynamic 2D array - arrays

sort of a newbie with VBA and I was wondering how you can create a dynamic 2D array which will be the size of the selected data in excel (Not knowing how big the data is) . I am unfamiliar with the VBA syntax and most of the questions I saw dealt with static data where the person knows the size of the excel table.
I have already created a function which automatically selects the data in the excel sheet. Now I wish to know how I can place all these data into a 2D Array.
Sorry if this is a common question, I am more familiar with 2D arrays with other languages, however I am getting mixed up with people using Range, Array and others in VBA
Also the data is strings in each element of the table. Please also advise how I will pull this data out :) Thank you

This code will put into array for you ..
Sub SelectionToArray()
Dim arrSelection() As String
Dim i As Integer
i = 0
ReDim arrSelection(i)
For Each c In Selection
arrSelection(i) = c.Value
i = i + 1
ReDim Preserve arrSelection(i)
Next c
End Sub

Related

How to get Excel Row as 1D object array into VB.net

I am trying to pull a row of data from an excel spreadsheet that I already have open, in order to compare it with an existing 1D array of values. As far as I can tell, when I try to pull a range such as
Dim excelArray(49) as object
excelArray = sheet1.Range("B3", "AY3").Value
it returns a 2d array, even though it only has a single row. This line in my code errors because of this. I need it to compare with another array that is already populated which is actually an array of Singles. The above excel row also contains a row of singles in each cell.
Dim otherArray(49) as object
Is there a way to do this that does not involve the following.
For i As Integer = 2 To 51
indexJ = i - 2
excelArray(indexJ) = sheet1.Cells(3, j).value
Next j
I do not wish to do it the above way because I am doing this with several large arrays, multiple times. The process of doing it cell by cell seems to be taking a long time.

Looking to read the .text of cells into an array

I'm building a simple report compare macro in Excel VBA to compare all sorts of different reports in our system. Since it's so much faster I'm pulling both spreadsheets into arrays and running a compare on them then pasting the results into a different workbook.
The issue is that both spreadsheets have long underlying values in some cells (interest rates and things like 3.27823202), but all I care about is the displayed value in the cell (3.28). I know I can easily pull the .values into an array with
Dim ReportParams() as variant
Dim SH1 as Worksheet
set SH1= activeworkbook.sheets("Sheet1")
ReportParams= SH1.range(cells(1,1),cells(5,5)).Value
But when I attempt the same using .Text instead of .Value it gives me a Run-Time error '13': Type Mismatch.
Is there any effecient way to bring in all the visible values for the cells into an array?

Excel vba and arrayformula

I'm trying to get the values from an array formula into VBA as an array. Simple example: I have a cell (let's say D1) which has an array formula in it such as
=A1:A10*B1:B10
when I highlight this on the spreadsheet and press F9 I'll get an array of 10 numbers, say, ={5;12;15;24;25;24;42;40;54;70}
I want to be able to store these values in a VBA array: a(0)=5, a(1)=12, a(3)=15 etc; you get the idea.
Tried hunting for an answer on this one, but can't find anything relevant even on MSFT. Lots of answers about how to go the other way from VBA to the worksheet range (I know that one) but not this way. Looked at trying to do it via a ParamArray (the number of elements won't be fixed), by assigning directly to a undimensioned array and via EVALUATE(range) but I can't get any of these to work. I feel I must be missing something obvious.
Not sure what you have tried already. But Evaluate should work.
If I have the following:
The code:
Sub getArrayFormulaResult()
sFormula = Range("D1").FormulaArray
aResult = Evaluate(sFormula)
MsgBox Join(Application.Transpose(aResult), ",")
End Sub
will result in:
try this
Dim var as variant
var=Worksheets("MySheet").Evaluate(Worksheets("MySheet").Range("D1").formula)
Note you should use Worksheet.Evaluate to ensure this works when Mysheet is not the active sheet. The result will always be a 2_D array (with one column for your example array formula)

What is the Best Method for Storing Data

I am creating a Word userform using VBA. I store several configuration using array in the program code, such as the following:
Public arrConfiguration[2, 3] as Integer
where index 2 represent type 0 to 2, and index 3 represent properties 0 to 3 for each type.
However, I planned to modify the program for larger amount of data (such as for 100 different types of data and 50 properties for each data).
My question is,
should I keep storing the data using array in the program, so that it will be
Public arrConfiguration[99, 49] as Integer
or store it in an Excel file, and make the program open the Excel file and access the cells repeatedly? Which one is better?
Thank you.
Please prefer excel. Sample example data image is appended here-under.
For cre­at­ing two dimen­sional dynamic array in excel, fol­low the steps below:
◾Declare the two dimen­sional Array
◾Resize the array
◾Store val­ues in array
◾Retrieve val­ues from array
Sub FnTwoDimentionDynamic()
Dim arrTwoD()
Dim intRows
Dim intCols
intRows = Sheet1.UsedRange.Rows.Count
intCols = Sheet1.UsedRange.Columns.Count
ReDim Preserve arrTwoD(1 To intRows, 1 To intCols)
For i = 1 To UBound(arrTwoD, 1)
For j = 1 To UBound(arrTwoD, 2)
arrTwoD(i, j) = Sheet1.Cells(i, j)
Next
Next
MsgBox "The value is B5 is " & arrTwoD(5, 2)
End Sub
In the Message Box you will get the following output.
Further To visualize a two dimensional array we could picture a row of CD racks. To make things easier, we can imagine that each CD rack could be for a different artist. Like the CDs, the racks would be identifiable by number. Below we'll define a two dimensional array representing a row of CD racks. The strings inside of the array will represent album titles.
For multidimensional arrays it should be noted that only the last dimension can be resized. That means that given our example above, once we created the array with two CD racks, we would not be able to add more racks, we would only be able to change the number of CDs each rack held.
You can simplify #skkakkar code:
dim x as variant
x = range("A1").CurrentRegion
No Redim, no loops.
Depending on how you see things evolving, you might want to consider accessing your Excel data via ADO, rather than OLE Automation. That way, if you decide to change your storage system to Access, SQL Server or something else, you will have less work to do.
How To Use ADO with Excel Data from Visual Basic or VBA (Microsoft)
https://support.microsoft.com/en-gb/kb/257819
Read and Write Excel Documents Using OLEDB (Codeproject)
http://www.codeproject.com/Tips/705470/Read-and-Write-Excel-Documents-Using-OLEDB

Populating an Array in VBA from different parts of a spreadsheet

I am trying to populate different portions of an array based on different locations within a spreadsheet.
For example
Dim prices(50) as double
prices(0, 1, 2) = Range("i35", "i38")
prices(3,4,5,6,7,8) = Range("b7","b12")
I'm getting a wrong number of dimensions error, because I'm assuming you have to populate the whole thing at once. Is there another syntax to do this better, or is it just a limitation of VBA?
Possibly a for each loop? But that doesn't really help since there are a lot of different ranges.
Thanks for your help
It looks like you are trying to tell VBA that the list of numbers in the parenthesis of the array are positions within an array that will receive multiple items.
That's not what it is. Instead, you can only do one at a time. For example:
Dim prices(50) as double
' My range syntax might be wrong here.
prices(0) = Range("i35", "i35")
prices(1) = Range("i36", "i36")
prices(2) = Range("i37", "i37")
prices(3) = Range("i38", "i38")
..etc. Or, if you're new to programming, you'll find this really cool:
for CounterVariable = 0 to 3
prices(CounterVariable) = Range("i" & 35 + CounterVariable)
next CounterVariable
To Wit ...
an array defined like Dim prices(50) will have one 'dimension', like a straight line.
Picture one row in a spreadsheet, 50 columns long.
If you said Dim prices(50,60) you would have a 2-dimensional array, like a cartesian plane (x,y) or a 50x60 cell spreadsheet where the first number is like the letters, the second, like the numbered rows.
Some languages support 3-dimensional arrays - VariableName(x,y,z). Don't know if VBA does
Therefore, using commas in parenthesis after an array is supported by VBA
BUT it means something completely different than you were hoping (and you can't change that): the values for the dimensions.
So your last line of code is looking for some value in a 6-dimensional universe! So we've got, height, width, depth, time, tesseract, and uh, you've beat me there!!!

Resources