column to matrix VBA - excel

I need to reformat a single column (range) of 100+ thousand integers to a user defined matrix of rows and columns. All my online searches have been disappointing in that they're too complicated or not exactly what I need. Index and Offsets won't due because the matrix dimensions (300+ cols, 300+ rows) would be prohibitive for copying over and down. A function would be sufficient that includes the range index, num_cols, num_rows.
Thanks in advance.

So assuming I understand your question (and if not I will withdraw this answer, just let me know), the following entered as an array formula in the spot you want your answer to land should work. InputCol would be where the data now sit. I am not checking sizes and such. You may soup it up to do that. If this is indeed what you want, someone can probably make it do a little better by copying a row (using Application.WorksheetFunction.Transpose) at a time (though I suspect that gets into offset and less readability).
Function SoTest(ByRef inputCol As range, NumRows As Long, NumCols As Long) As Variant
Dim NewMatrix() As Variant
Dim i, j, k As Long
ReDim NewMatrix(1 To NumRows, 1 To NumCols)
k = 1
For i = 1 To NumRows
For j = 1 To NumCols
NewMatrix(i, j) = inputCol(k, 1)
k = k + 1
Next j
Next i
SoTest = NewMatrix
End Function

Related

Get values for all columns with value greater than 0

I am using Libre Calc with a horizontal table like below
a
b
c
d
e
f
g
h
I
j
0.1
0.7
2.3
5
And i would like to list values greater than 0 like below
Name
Value
b
0.1
e
0.7
f
2.3
g
5
I have tried to use INDEX and MATCH with no success How to use Index to find all values greater than
=INDEX($R$4:$R$13,MATCH(1,($S$4:$S$13>0)*(COUNTIF($U$3:U3,$R$4:$R$13)=0),0))
I have also tried to create a separate Transpose of table and then run the above command with limited success.
This task can be accomplished in several different ways.
The first option (which you tried) is with a long and obscure formula. More precisely, two formulas - the first will select the names of the columns that should be displayed, the second will pull the necessary values into the resulting table using the selected names (this can be an ordinary HLOOKUP())
(By the way, the formula that you tried to use is already morally outdated - now Excel has a FILTER() function, which, in combination with the TRASPOSE() function, will give the desired result much easier. Let's hope that Calc will soon also get functions like FILTER(), UNIQUE() and others)
Another way is to manually copy the original range, paste it into a new location using Paste Special (Ctrl+Shift+V) with the Transpose and Link options enabled, and then filter the resulting auxiliary range using the usual Standard filter, copying the filtering result to the specified location.
I prefer the third way - UDF, User-defined function. The task is quite simple, the usual movement of data from place to place. Therefore, the algorithm is also simple and the macro code too:
Function TransposeAndFilter(aData As Variant) As Variant
Dim aResult As Variant
Dim lB1 As Long, uB1 As Long
Dim lB2 As Long, uB2 As Long
Dim i As Long, j As Long, nextRow As Long
lB1 = LBound(aData, 1) : UB1 = UBound(aData, 1)
lB2 = LBound(aData, 2) : UB2 = UBound(aData, 2)
ReDim aResult(lB2 To uB2, lB1 To uB1)
nextRow = lB2 - 1
For i = lB2 To uB2
If aData(uB1,i) > 0 Then
nextRow = nextRow + 1
For j = lB1 To uB1
aResult(nextRow, j) = aData( j, i)
Next j
EndIf
Next i
TransposeAndFilter = aResult
End Function
Write in a cell a formula like as =TRANSPOSEANDFILTER(A1:I2) and press Ctrl+Shift+Enter

Draw a Tree/Lattice with VBA using an Array

I'm trying to generate a binomial tree for option evaluation, and I want to draw a lattice using values that comes from an array where values are already there.
So basically I have an array in my VBA that ressemble to this:
My array in vba
And I want to paste in an Excel sheet in this form:
How i want to paste in my worksheet
I don't necessarily ask for a code, I would just like to have an idea of the algorithm used to create the tree. I really tried to see any pattern and couldn't find.
What I identified is that if the number of columns of the array is (n+1), then then number of rows will be (2n-1).
Thanks in advance
This might give you an idea. You would need to tweak it if your array is not 1-based:
Sub InsertTree(Nodes As Variant, RootNode As Range)
'Assumes that Nodes is a 1-based array
'That has data 1-element in its first
'column, 2 in its second, etc. And that RootNode
'Has been chosen so that there is enough room
'for the tree
Dim i As Long, j As Long, n As Long
Dim TopNode As Range 'top node in each column
n = UBound(Nodes, 2)
Set TopNode = RootNode
For j = 1 To n
For i = 1 To j
TopNode.Offset(2 * (i - 1)).Value = Nodes(i, j)
Next i
If j < n Then Set TopNode = TopNode.Offset(-1, 1)
Next j
End Sub
As a test, I set my spreadsheet up so that beginning at A1 I had:
a b d g
c e h
f i
j
Then I ran:
InsertTree Range("A1:D4").Value,Range("F10")
And the result looks like this:

Remove approximate matching numbers from two column (Amt1 and Amt 2)

Need help with VBA code to remove approximate matching numbers from two columns that is Amt1 and Amt 2:
Amt 1 Amt 2
412.82 0
671.44 0
54.25 412.83
574.89 671.44
0 484.2
0 370.53
0 54.25
0 574.9
0 594.43
Desired Result: I want 412.82 from column Amt 1 and 412.83 from column Amt 2 should be removed from both the columns.
Sub removedup()
Dim source As Range
Dim iCol1 As Long
Dim iCol2 As Long
Dim nRow1 As Long
Dim nRow2 As Long
Dim nCol As Long
Dim nRow As Long
Set source = Selection
nCol = source.Columns.Count
nRow = source.Rows.Count
iCol1 = 1
iCol2 = 2
For iRow1 = 1 To nRow
For iRow2 = 1 To nRow
If (Cells(iRow1, iCol1) - Cells(iRow2, iCol2) >= -3) And (Cells(iRow1, iCol1) - Cells(iRow2, iCol2)) <= 3 Then
Cells(iRow1, iCol1) = ""
Cells(iRow2, iCol2) = ""
End If
Next iRow2
Next iRow1
End Sub
Actually this task would be much more complicated as you think
To find similar values you would need to work with the distances between these values and if the distance is smaller than a defined threshold then they are considered as being "similar".
But it gets really hard if there are more similar distance.
My thoughts, imagine the following data:
If you define that a distance <= 0.02 is considered as similar then the following pairs are considered as similar:
Scenario 1
You start comparing from the top and you find that 412,84 and 412,83 are similar and delete them immediately. Then you will remain with 412,81 and 412,85 which are not similar (distance is 0.04) and they will be kept.
Scenario 2
You compare first 412,84 and 412,85 and delete them as similar then you will remain with 412,81 and 412,83 and they will also be deleted as similar. No values will be kept at all.
What does that mean?
There is not only one solution for this szenario and you will get different results on the same data-set (with differently ordered values). So you have to calculate all of the scenarios and decide which one is the correct one, because your algorithm can't decide that.
What to do now?
Re-think what your actual problem is. Define new rules so that there will be only one definite solution for a case like this. Otherwise you will get random results.
Probably you asked the wrong question.

repeating macro

I am looking for a marcro that can copy and paste cells.
The value of cell X must be copied to a cell X + 6.
So A1 text "Xteam" has to be copied to cell A7, this up to cell A380.
The same applies to cell B2 + 6.
It has to be dynamic, so the cell and sequence are dynamic..
I want to be able to indicate for myself which cell it is and the sequence ..
How can I do this,
I have this but doesnot work like i want:
Sub sequence()
Const Nxt As Long = 7
Dim A As Variant, B As Variant, V As Variant, N As Long
A = Range("A1").Value
B = Range("B2").Value
ReDim V(Nxt To 380, 1 To 2)
For N = Nxt To 380
If N Mod 6 = 1 Then
V(N, 1) = A
V(N + 1, 2) = B
End If
Next N
Application.ScreenUpdating = False
Range("A" & Nxt, "B380").Value = V
Application.ScreenUpdating = True
End Sub
thank you in advance
elmalle
Ok well, this is under the assumption that you want to specify how many times you want to copy A1 and B2 down the sheet. So your loop is fairly confusing, instead of using MOD, since you know you want it every 6 spaces and you're not doing anything to the other cells, it's easier just to have the number multiplied by 6 for your indexing. This also helps you figure out the dimensions of your transfer arrays more easily since you want to specify how many times you want to copy.
It's also worth noting that you're Application.screenupdating = False is in the wrong place. The real place you would want to speed up is during the loop. So if you were to include it, I would put it near the top of the code, but this isn't very resource intensive so I've just left it out.
Normally it's good to dim Constants if it helps with the legibility of the code, but in this case it doesn't seem to add any clarity. An example where it could help is where you're changing the colour of cells and are using colour indices. Constant Red as long = 3 makes it a lot more understandable, whereas constant Nxt as long = 7 doesn't add much.
Instead of working with a 2-D array dealing with both A and B at once, I chose to use two column vectors because it makes the pasting easier since they are staggered and it simplifies the math since you don't need to have items on staggered rows.
Lastly, I can't advocate this enough, but please, please, please use names that make sense at a glance. Although it may not have made a huge difference in this case, if you get to a more complicated project people might look at it and have to wonder what V is even used for. It also just makes it easier for people to help you since they won't have to sit for a bit wondering what each variable means.
I've also specified the worksheet it looks at, so currently it'll only look at the first sheet as indicated by the index 1. Make sure you change that so it changes the correct sheet.
Hope this helped and welcome to Stack Overflow.
Option Explicit
Sub sequence()
Dim A As Variant
Dim B As Variant
Dim N As Long
Dim ArrA() As Variant
Dim ArrB() As Variant
Dim NumCopies As Long
A = Range("A1").Value
B = Range("B2").Value
NumCopies = 100
ReDim Preserve ArrA(1 To NumCopies * 6, 1 To 1)
ReDim Preserve ArrB(1 To NumCopies * 6, 1 To 1)
For N = 1 To NumCopies
ArrA(N * 6, 1) = A
ArrB(N * 6, 1) = B
Next N
Worksheets(1).Range("A2:A" & 1 + NumCopies * 6).Value = ArrA
Worksheets(1).Range("B3:B" & 2 + NumCopies * 6).Value = ArrB
End Sub

How can I "ReDim Preserve" a 2D Array in Excel 2007 VBA so that I can add rows, not columns, to the array?

I'm working with a dynamic array in Excel VBA. The number of columns (m) is fixed, however, I do not know how many rows (n) will be required.
The help documents state that ReDim Preserve myArray(n, m) allows me to make m larger, but not n. However, I need to increase the number of rows (n) while preserving my data, not columns (m)!
For example, I may have a (5,20) array that I would like to expand to (10,20) while preserving my data.
It seems that if there were some way to transpose my array, do a ReDim Preserve to expand the number of "columns", then re-transpose my array, I could accomplish what I want.
Is this the correct way to do this? If so, how can I do that?
Is there a better way to accomplish what I want?
One way to do what you want is to use a 1-D array that contains 1-D arrays instead of a 2-D array. Then you can ReDim Preserve the outer array all you want. If you're returning the outer array from a function, Excel will do the right thing and coerce it to a 2-D array.
For example, the function below will return a 3x2 array to the cells it's called from:
Public Function nested()
Dim outer
outer = Array(Array(1, 2), Array(3, 4))
ReDim Preserve outer(1 To 3)
outer(3) = Array(5, 6)
nested = outer
End Function
My answer to these questions might also be useful to you: Pass multidimensional array into Excel UDF in VBA and VBA pasting 3 dimensional array into sheet
Of course, if you're not returning this from a UDF, you'll have to coerce it yourself. An easy way to do that without writing looping code is to do this:
Dim coerced
coerced = Application.Index(outer, 0, 0)
This is just calling Excel's built-in INDEX function, and the zeros mean that you want back all of your rows and all of your columns. Excel will coerce your 1-D array of 1-D arrays to a 2-D array automatically. (Caveat: there are some size limitations, but they are much bigger than 10x20.)
One way how you could sove it is indeed by a double transpose with a change on the number of columns in between. This will however only work for two-dimensional arrays. It is done as follows:
' Adding one row is done by a double transposing and adding a column in between.
' (Excel VBA does not allow to change the size of the non-last dimension of a
' multidimensional array.)
myArray = Application.Transpose(myArray)
ReDim Preserve myArray(1 To m, 1 To n + 1)
myArray= Application.Transpose(myArray)
Of course m and n can be deduced as follows:
m = UBound(myArray, 1)
n = UBound(myArray, 2)
So you use the built-in transpose functionality of Excel itself. As mentioned in the code comments, this will not work for higher order matrices.
If you are developer - what is the difference between rows and columns?
Using array(N, 2) (if you have 2 columns) is the same as array(2, N) - for which you can
ReDim Preserve arr(1 to 2, 1 to N+1).
And the difference for you (as developer) will be to put the variable from the cycle in second place, instead of the first one:
N = ubound(arr)
FOR i=1 to N
GetColumn1Value = arr(1, i)
GetColumn2Value = arr(2, i)
NEXT i
Or you want this:
N = ubound(arr)
FOR i=1 to N
GetColumn1Value = arr(i, 1)
GetColumn2Value = arr(i, 2)
NEXT i
What is the difference?
Solved my own question; here's how I got around my problem. I created a temporary array, copied the contents of myArray to the temporary Array, resized myArray, then copied the contents back from the temp array to myArray.
tempArray = myArray
ReDim myArray(1 To (UBound(myArray()) * 2), 1 To m)
For i = 1 To n
For j = 1 To m
myArray(i, j) = tempArray(i, j)
Next j
Next i
If anyone can suggest a more efficient way to do this, I'd love to hear it.
The word 'transpose' immediately leaps to mind. You could simply enter data into the 2D array by flipping the columns and rows (i.e. transpose), effectively allowing you to make n (now the number of columns, but storing row values) larger when you require.
To reference the values, say in a double loop, swap the indices around. E.g. rather go from i = 1 to n and j = 1 to m where you reference value(i, j) , use i = 1 to m and j = 1 to n.
No way to determine the number of elements in the first dimension? Bummer. For a two-dimensional array with a fixed second dimension, you might want to consider making it an array of Types ("structs" in other languages) instead. That will allow you to use Redim Preserve, and still leaves you with a reasonable way to add and access values, though you'll now be accessing the second dimension as named members of the Type rather than is index values.
coercing or Slicing doesnt seem to work with Index( or Match(Index( when i want to filter array (w/o loops) based on multiple criteria, when the size of data spans greater than 2^16 rows (~ 92000 rows).
Run-Time error '13':
Type Mismatch
Transpose doesnt work with large recordsets and so also double Transpose does not work. isn't there anyway to filter an array and grab data without resorting to multiple loops?
I am thinking of trying the dictionary way or ADO with Excel.
A Caution on Redim Preserve
The urge to use ReDim Preserve here is likely misguided. Per Ken Getz and Mike Gilbert in the VBA Developer's Handbook (2006):
Using ReDim Preserve does preserve the contents of your array as it's
being resized, but it's not a fast operation... VBA must grab a chunk
of memory for the new array and then... copy over all the items in
your original array. Finally, it releases the memory used by the
original array. You'd do best to avoid ReDim Preserve if at all
possible.
Matthew Curland, a Microsoft VB developer, similarly noted in Advanced Visual Basic 6: Power Techniques for Everyday Programs (2000):
Suppose you anticipate needing 100 items up front, but... you
suddenly need space for number 101. The first reaction is a call to
ReDim Preserve to simply make the array larger. However, this call
gets more and more painful from a performance standpoint as the system
grows. You request more and more memory and possibly touch all the
memory you've previously filled. Even if you ReDim Preserve in chunks
instead of one element at a time, you'll find that the ReDim call is
the slowest part of the system.
In other words, ReDim Preserve is not as magical as it first appears. If you add one at a time, you'll see performance problems.
Now, copying an array by looping is slower yet. According to Curland, "VB's ReDim statement maps to the SafeArrayCreate[Ex] API, ReDim Preserve maps to SafeArrayRedim, and Erase maps to SafeArrayDestroy." Those APIs are much faster than loops. However, if you have to transpose the array to get there, it probably isn't worth it.
The direct way
For copying over by loop, the following sub will work. For limited use, it should be faster than transposing.
Sub RedimPreserveRows(source As Variant, newRowBound As Long)
'For 2d arrays, this copies the old data to a new array with a new Ubound for the first dimension (rows)
Dim rowBound As Long: rowBound = UBound(source)
Dim columnBound As Long: columnBound = UBound(source, 2)
Dim fillRowBound As Long: fillRowBound = IIf(newRowBound > rowBound, rowBound, newRowBound)
Dim returnArray()
ReDim returnArray(newRowBound, columnBound)
For i = 0 To fillRowBound
For j = 0 To columnBound
returnArray(i, j) = source(i, j)
Next
Next
source = returnArray
End Sub
For more: A question on alternatives to Redim Preserve was recently asked here, and I just reviewed some other options for resizing arrays in an answer here.
An array with 2 dimensions, where the number of columns are fixed and the number of rows are dynamic, can be created like this:
Sub test2DimArray()
Dim Arr2D() As String
Dim NumberOfCol As Long
Dim I As Long, J As Long, x As Long
Dim tmpValue As String, tmpValue2 As String, tmpValue3 As String
NumberOfCol = 3
J = 1
Debug.Print "Run " & Now()
Debug.Print "Sheet content"
Debug.Print "Row col1 col2 col3"
For I = 1 To 10
tmpValue = Cells(I, 1).Value
tmpValue2 = Cells(I, 2).Value
tmpValue3 = Cells(I, 3).Value
Debug.Print I & " = " & tmpValue & " " & tmpValue2 & " " & tmpValue3
If Len(tmpValue) > 0 Then
ReDim Preserve Arr2D(NumberOfCol, 1 To J)
Arr2D(1, J) = tmpValue
Arr2D(2, J) = tmpValue2
Arr2D(3, J) = tmpValue3
J = J + 1
End If
Next
'check array values
Debug.Print vbLf; "arr2d content"
Debug.Print "Row col1 col2 col3"
For x = LBound(Arr2D, 2) To UBound(Arr2D, 2)
Debug.Print x & " = " & Arr2D(1, x) & " " & Arr2D(2, x) & " " & Arr2D(3, x)
Next
Debug.Print "========================="
End Sub
TempValue read from cells A1:A10, if there is a value in cell Ax, it redim the array with +1, and add Tempvalue to array col1, add contents in Bx to array col2 and contents in Cx to array col3. If length of Ax-value is 0, it does not add anything to the array.
Debug.print show results in the "immediate window" in the VB editor.
Without the testing lines, and adding a dynamic data-range the code can be:
Sub my2DimArray()
Dim Arr2D() As String
Dim NumberOfCol As Long, NumberOfRow As Long
Dim FirstCol As Long, FirstRow As Long, LastCol As Long, LastRow As Long
Dim I As Long, J As Long, X As Long
Dim tmpValue As String, tmpValue2 As String, tmpValue3 As String
'if cells with values start in A1
With ActiveSheet.UsedRange
NumberOfCol = .Columns.Count
NumberOfRow = .Rows.Count
End With
'if cells with values starts elsewhere
With ActiveSheet.UsedRange
FirstCol = .Column
FirstRow = .Row
LastCol = .Column + .Columns.Count - 1
LastRow = .Row + .Rows.Count - 1
End With
J = 1
For I = 1 To NumberOfRow 'or For I = FirstRow to LastRow
tmpValue = Cells(I, 1).Value 'or tmpValue = Cells(I, FirstCol).Value
If Len(tmpValue) > 0 Then
ReDim Preserve Arr2D(NumberOfCol, 1 To J)
For X = 1 To NumberOfCol 'or For X = FirstCol to LastCol
Arr2D(X, J) = Cells(I, X).Value
Next X
J = J + 1
End If
Next I
End Sub

Resources