Displaying some values from an array VBA excel - arrays

I'm trying to display multiple values on my excel file based on first line and first column. I've made a 2D array for my values. MyValue is an InputBox variable and I loop over the first column trying to find MyValue and I want to get on display values that are on "PSC", "BCCH" and so on columns, basically the same thing as a filter based on 1st column but displaying only some values from other columns. The output that i have for this operation is in this image:
However 136, 144 and 152 which are PSC values are on line 2, 3, 4 in my source excel file, I'm not sure what are those zeros. I want to diplay those values one under each other, I tried without offset method but if I don't use it I get no value displayed.
Dim1 = wSht.Range("A2", wSht.Range("A1").End(xlDown)).Cells.Count
Dim2 = wSht.Range("A1", wSht.Range("A1").End(xlToRight)).Cells.Count
For i = 1 To Dim1
For j = 1 To Dim2
If wSht.Cells(i, 1) = MyValue Then
If wSht.Cells(1, j) = "PSC" Then
ReDim Preserve Matrice(0 To 5, 0 To Matrice_size)
Matrice(0, Matrice_size) = wSht.Cells(i, j).value
Matrice_size = Matrice_size + 1
End If
If wSht.Cells(1, j) = "BCCH" Then
ReDim Preserve Matrice(0 To 5, 0 To Matrice_size)
Matrice(1, Matrice_size) = wSht.Cells(i, j).value
Matrice_size = Matrice_size + 1
End If
End If
Next j
Next i
For k = LBound(Matrice, 1) To UBound(Matrice, 1)
For l = LBound(Matrice, 2) To UBound(Matrice, 2)
ThisWorkbook.Worksheets(1).Range("A2").Offset(k, l).value = Application.Transpose(Matrice(k, l))
Next l
Next k

switch the first If line with the For j and also the corresponding last End If with the Next j, so the inner loop only runs through the correct rows.
it seems the data starts at line 2, so start the For i loop with 2.
if you only need data from those two columns you can look for them in a separate loop first and save their position, so you don't need a nested loop. (in this case my first point doesn't apply).
you don't even need a loop, you can use Excel's MATCH function.
the matrix and transpose seems to be an overkill. since i determines k and l you can get rid of this part, and write to Worksheets(1) directly from the i-j loop.
you have five rows in the matrix and every fifth output is a correct value, isn't that suspicious?
you seem to put values into line 0 and 1 of the matrix then read from line 1 and 2. this might be the reason for the line full of 0s
if you can provide what exactly you would expect from what exact source data, I can help you more. but without knowing, my solution would look something like
PSC_col = Application.WorksheetFunction.Match("PSC", wSht.Rows(1).EntireRow, 0)
BCCH_col = Application.WorksheetFunction.Match("BCCH", wSht.Rows(1).EntireRow, 0)
For i = 2 To wSht.[A2].End(xlDown).Row
If wSht.Cells(i, 1) = MyValue Then
ThisWorkbook.Worksheets(1).[A2].Offset(k, 0).Value = wSht.Cells(i, PSC_col).Value
ThisWorkbook.Worksheets(1).[B2].Offset(k, 0).Value = wSht.Cells(i, BCCH_col).Value
k = k + 1
End If
Next i

Related

Aggregating part of a 2d array in a column in said array

I have a 2d array, with flexible dimensions:
arr_emissions(1 to n, 0 to m)
Where n is 22 or larger, and m is 6 or larger.
In the smallest case column m = 6 should contain the sum of columns m = 2 - 5.
I could ofcourse simply add them, but as the dimensions of the array are flexible I would like to implement a more robust method, that preferly doesn't loop over the entire array.
I was hoping to implement the native application.WorksheetFormula.Sum(). I saw an implementation in this answer, but that only works for complete rows or columns.
Example:
I have arr_emissions(0 to 111,1 to 6). It is populated in a loop from 1 to 111.
The data in the array is as follows:
(1,1) #3-4-2020# 'a date value
(1,2) 1,379777
(1,3) 0
(1,4) Empty
(1,5) Empty
Don't know if this helps, but this takes a source array v and then populates a new array w with the sum of columns 2-4 of the corresponding row of v.
Sub x()
Dim v, i As Long, w()
'just to populate source array
v = Range("A1").CurrentRegion.Value
ReDim w(1 To UBound(v, 1))
For i = 1 To UBound(w)
'each element of w is sum of columns 2-4 of corresponding row of v
w(i) = Application.Sum(Application.Index(v, i, Array(2, 3, 4)))
Next i
'write w to sheet
Range("G1").Resize(UBound(w)) = Application.Transpose(w)
End Sub
Thanks to the answer from SJR I found myself a working solution. This is all within a larger piece of code, but for this example I filled some variables with fixed numbers to match my example from my question.
Dim days as Integer
days = 111
Dim emissions_rows as Integer
emissions_cols = 6
ReDim arr_emissions(0 To days, 1 To emissions_cols) As Variant
Dim arr_sum As Variant
Dim sum_str As String
sum_str = "Transpose(row(2:" & emissions_rows - 1 & "))"
arr_sum = Application.Evaluate(sum_str) '= Array(2,3,4,5)
arr_emissions(emissions_index, emissions_cols) = Application.Sum(Application.Index(arr_emissions, emissions_index + 1, arr_sum))
The code writes a string to include the variables, so to take the second column untill the second to last column, which is then evaluated into an array.
That array is then used within the sum function, to only sum over those columns.
The result is then written to the last column of arr_emissions().
emissions_index is an index that is used to loop over the array.

How to Pass an Array to and from a Function?

(Fair Warning, I am self taught on VBA so I apologize in advance for any cringe-worthy coding or notations.)
I have an estimating worksheet in excel. The worksheet will have a section for the user to input variables (which will be an array). The first input variable will "reset" the remaining input variables to a standard value when the first variable is changed. The standard values for the input variables are stored in a function in a module. I am attempting to fill the input variable array with the standard values from the function and then display those values on the sheet. I was easily able to do this without arrays but have had no luck in moving everything into arrays.
This is for excel 2010. I previously did not use arrays and created a new variable when needed, however the estimating sheet has grown much larger and it would be better to use arrays at this point. I have googled this question quite a bit, played around with removing and adding parenthesis, changing the type to Variant, trying to set the input variable array to be a variable that is an array (if that makes sense?), and briefly looked into ParamArray but that does not seem applicable here.
Dim BearingDim(1 To 9, 1 To 4, 1 To 8) As Range
Dim arrBearingGeneral(1 To 5, 1 To 8) As Range
Dim Test As Variant
Private Sub Worksheet_Change(ByVal Target As Range)
'Set General Variable array to cells on the worksheet
For i = 1 To 5
For j = 1 To 8
Set arrBearingGeneral(i, j) = Cells(9 + i, 3 + j)
Next j
Next i
'Set Bearing Input Variables to Cells on the Worksheet
For p = 1 To 4
For i = 1 To 9
Select Case p
Case Is = 1
Set BearingDim(i, p, 1) = Cells(16 + i, 4)
Case Is = 2
Set BearingDim(i, p, 1) = Cells(27 + i, 4)
Case Is = 3
Set BearingDim(i, p, 1) = Cells(37 + i, 4)
Case Is = 4
Set BearingDim(i, p, 1) = Cells(49 + i, 4)
End Select
Next i
Next p
'Autopopulate standard input variables based on Bearing Type
inputMD_StdRocker BearingType:=arrBearingGeneral(1, 1), _
arrBearingDim:=BearingDim
End Sub
Sub inputMD_StdRocker(ByVal BearingType As String, ByRef _
arrBearingDim() As Variant)
Dim arrBearingDim(1 To 9, 1 To 4)
Select Case BearingType
Case Is = "MF50-I"
For j = 1 To 2
arrBearingDim(2, j) = 20
arrBearingDim(3, j) = 9
arrBearingDim(4, j) = 1.75
Next j
arrBearingDim(5, 1) = 15
'There are numerous more select case, but those were removed to keep it
'short
End Select
End Sub
The expected output is my "BearingDim" Array will have certain array index values set to a standard value from the "inputMD_StdRocker" function. Then those values will be displayed in the cell that corresponds to the array index.
Currently, I get a compile error "Type Mismatch, Array or User-Defined Type Expected". I have been able to get around the type mismatch by removing the () from "arrBearingDim()" in the function title for "inputMD_StdRocker" however, it will not pass the values back to my "BearingDim" array.
Any help would be greatly appreciated.
This is a partial answer to what (I think) is a misunderstanding you have of how to use arrays. There are a few problems in your code.
First, you're defining a two-dimensional and a three-dimensional array of Ranges when I believe you really only want to store the values captured from the worksheet. (If I'm wrong, then you are never initializing the array of Ranges, so none of the ranges in the array actually point to anything.)
Secondly, it looks as if your initial array arrBearingGeneral is always filled from the same (static) area of the worksheet. If this is so (and you really do want the values from the cells, not an array of Range objects), then you can create a memory-based array (read this website, especially section 19). So the first part of your code can be reduced to
'--- create and populate a memory-based array
Dim bearingDataArea As Range
Dim arrBearingGeneral(1 To 5, 1 To 8) As Variant
Set bearingDataArea = ThisWorkbook.Sheets("Sheet1").Range("D10:K14")
arrBearingGeneral = bearingDataArea.Value
Optionally of course you can calculate the range of your data instead of hard-coding it ("D10:K14"), but this example follows your own example.
While this isn't a complete answer, hopefully it clears up an issue to get you farther down the road.

Compare two arrays and delete identical values

My goal is to delete all identical rows from a sheet.
I created two arrays. One is the "current row" (1) and the second array is refilled with one row after the other. This part works.
Now I want to match the two arrays and if they are identical the corresponding row should be deleted.
Then the "current row" changes to 2.
For j = 1 To VarAnzahlZeilen
i = 1
For i = 1 To VarAnzahlSpalten
ReDim Preserve ArrAktuelleZeile(i - 1) As String
ArrAktuelleZeile(i - 1) = Worksheets("Filter").Cells(j, i).Value
Next i
(i+1)
For n = j + 1 To VarAnzahlZeilen
k = 1
For k = 1 To VarAnzahlSpalten
ReDim Preserve ArrDurchlaufZeile(k) As String
ArrDurchlaufZeile(k - 1) = Worksheets("Filter").Cells(n, k).Value
Next k
If Not IsError(WorksheetFunction.Match(ArrAktuelleZeile, ArrDurchlaufZeile, 0)) Then
Rows(n).Delete
End If
Next n
Next j
The Runtime Error 13 appears at line:
If Not IsError(WorksheetFunction.Match(ArrAktuelleZeile, ArrDurchlaufZeile, 0)) Then
I tried the idea of #GTPV and modified it slightly to fit my needs (variable Range and comparing columns 1-30).
A syntax error appears
Worksheets("Filter").Range(.Cells(1, 1), .Cells(VarAnzahlZeilen, VarNutzerSpalte))).RemoveDuplicates Columns:=Array(1, 2, 3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30), Header _
:=xlNo
One possibility is to use the built-in function from Excel which removes duplicates:
Worksheets("Filter").Range("$A$1:$C$10").RemoveDuplicates Columns:=Array(1, 3), Header _
:=xlNo
The above example will remove all duplicates in the range A1:C10 where a duplicate means "same value in column A AND same value in column C". This last parameter is controlled by the "Columns:=Array(1,3)" argument.
Getting only unique values based on column A alone would be coded as:
Worksheets("Filter").Range("$A$1:$C$10").RemoveDuplicates Columns:=Array(1), Header _
:=xlNo
Getting unique values based on the combination of all columns:
Worksheets("Filter").Range("$A$1:$C$10").RemoveDuplicates Columns:=Array(1,2,3), Header _
:=xlNo
Additional help on this function can be found on Microsoft website.

New array in For Next loop every iteration VBS

I have a section of code which opens each text file in a folder and I want to not only put the file name into an array but also split the text inside the file into an array, something like this:
i = 0
n = 1
For Each File In Folder
i = i + 1
Dim UserArray & i()
Set openedFile = fso.OpenTextFile(File)
Do Until openedFile.AtEndOfStream
Line = openedFile.ReadLine
ReDim Preserve UserArray & i(n)
UserArray & i(n) = Line
n = n + 1
Loop
n = 0
Loop
The idea being that each line will later be strComp to another array of lines from a different text file.
So each file needs to create a unique array name for its text contents and the number of files in any given folder varies.
The above does not work,any ideas?
There are syntax errors in your code(Line 5,9,10 - fixed by using execute statements which allows you to declare variables dynamically during run time with different names) along with variable spelling mistakes(Line 8).
P.S. I am not making any changes to the logic applied here. Just trying to correct the mistakes.
i = 0
n = 0 'initialised to 0
For Each File In Folder
i = i + 1
Execute "Dim UserArray"&i&"()" 'used execute statement to declare arrays with new names based on the value of i for each file
Set openedFile = fso.OpenTextFile(File)
Do Until openedFile.AtEndOfStream
Line = openedFile.ReadLine 'corrected the spelling mistake here
Execute "ReDim Preserve UserArray"&i&"("&n&")"
Execute "UserArray"&i&"("&n&")="&Line
n = n + 1
Loop
n = 0
Loop
After this code, you should have UserArray1 for 1st file, UserArray2 for 2nd file and so on...
You could try an array of arrays. Like so:
Dim Userarray() As Variant
Dim subArray() As String
i = 0
n = 1
For Row = 0 To 4
i = i + 1
ReDim subArray(i)
For Each cell In ActiveSheet.Range(Cells(i, 1), Cells(i, 5))
ReDim Preserve subArray(n)
subArray(n) = cell.Value
n = n + 1
Next
ReDim Preserve Userarray(i)
Userarray(i) = subArray
n = 0
Next
(I didn't have files, so I was just using a range in Excel). I assume VBA is similar enough to VBScript for this to work...Results in the first row of data as an array in Userarray(1), the second row of data as an array in Userarray(2), etc.

build excel array from data items and a multiplier

first question on this site.
Been coming here to bask in the warm glow of the knowledge on offer for years! Please be gentle with me. ;)
I'm not a programmer but can muddle my way around excel but I have a problem in excel that I'm struggling to find a solution to.
I need to take a set of data and turn it into an array (or list) of all the occurrences of that data. For example a set of data (A,B,C) and an instances value for each item (2,1,3).
What I need to do is take those two items and create an array of all occurrences.
Like this:-
Data,Instances
A,2
B,1
C,3
Total 6
Result
1,A
2,B
3,C
4,A
5,C
6,C
(I hope that's clear - my rating isn't high enough to post a screenshot)
So, in this example I have 2 As, 1 B and 3 Cs giving a total of 6 items. To create the result I've run through the list 6 times listing each data item if it still has an occurrence (but an array/list that was AABCCC would be just as valid). For the full data set there could be as many as 12 different data items with any number of occurrences each from 1 to 12.
Somehow I think I'm overcomplicating a simple process but for the life of me I can't get my head around achieving the result I need.
Say we put your data in column A:
and run this short macro:
Sub croupier()
Dim N As Long, K As Long, i As Long, ary(), bry()
Dim v As String
N = Cells(Rows.Count, "A").End(xlUp).Row
ReDim ary(1 To N)
ReDim bry(1 To N)
For i = 1 To N
v = Cells(i, "A").Value
cry = Split(v, ",")
ary(i) = cry(0)
bry(i) = CLng(cry(1))
Next i
K = 1
While Application.WorksheetFunction.Sum(bry) > 0
For i = 1 To N
If bry(i) <> 0 Then
Cells(K, "B").Value = ary(i)
bry(i) = bry(i) - 1
K = K + 1
End If
Next i
Wend
End Sub
Our result is this:
We repeatedly run down column A placing the values in column B until the count of an item reaches zero.
When the overall count of items is zero, we stop.

Resources