I am new to VBA but have previous experience with PHP programming logic and various stats programming syntax. I am trying to write a code to search through a series of cell ranges for a specific value– if that value exists in the range I want it to insert a 1 into an array, and if it doesn’t to insert a 0.
My data look something like:
**Item R1 R2**
1121 1 3
1121 2
1121
1121 3 2
1121 3
1122 4 5
1122 3 5
1122 5
1122 4
1122 5
My end goal is to be able to sum the values in the array and count the total number of items with each rating. For example, in the sample above I would want to be able to produce:
Number of Items with Rating of 1 = 1
Number of Items with Rating of 2 = 1
Number of Items with Rating of 3 = 2
And so on.
The code I wrote was:
Sub Items()
Dim myArray() As Variant
Dim i As Integer
Dim k As Integer
i = 0
k = 0
R5 = Range("G(2+k):H(6+k)")
mycount = Application.WorksheetFunction.Sum(myArray)
Sheets("Operational").Select
For Each R5 In Range("G2:H206")
ReDim myArray(0 To i)
myArray(i) = Cell.Value
i = i + 1
k = k + 4
R5.Select
If R5.Value = "1" Then
myArray(i) = 1
Else
myArray(i) = 0
End If
Next
End Sub
I have 5 rows for each item so I thought I could approach this as a repeating, consistent loop. However I get an error when I try to run it – “Application-defined or object-defined error.”
I know this is probably not the best way and I am so new to this I don’t know where to start in troubleshooting. Any help would be much appreciated.
Also if anyone has a good reference for VBA structure/code or a beginner’s tutorial, let me know! I haven’t had much luck in finding any good references.
You’ll need to change a few things to make this work out. I’ve changed/added comments to your code below…
I have used the
Scripting.Dictionaryto get this. To use, you’ll need to reference theMicrosoft Scripting Runtimelibrary (see comments in code). This doesn’t do much useful, just prints the results to the immediate window, but you can modify to get what you need, I think.