Problem storing value in array - vb.net

I want to store value in array, from my database. I am using following code but it return error: "Object reference not set to an instance of an object."
Code is:
Dim w as integer=0
Do While DsChooseSQsNow.tblChooseSQs.Rows.Count > w
vrSQsNoChosen(w) = DsChooseSQsNow.tblChooseSQs.Rows(w).Item("QNo")
vrTotalSQsChosen = vrTotalSQsChosen + 1
w = w + 1
Loop
Error comes on "vrSQsNoChosen(w) = DsChooseSQsNow.tblChooseSQs.Rows(w).Item("QNo")"

try to print the value DsChooseSQsNow.tblChooseSQs.Rows(w).Item("QNo")
or debug the code
"Object reference not set to an instance of an object." means Item("QNo") may be null

There are many reasons why this code fails. I would start checking from:
Size (and boundings) of vrSQsNoChosen array.
w value when error occurs (is valid index for vrSQsNoChosen array and Rows collection?).
Item("QNo") value when error occurs (maybe is null?).
Also -- VB.NET implements += operator so you can write:
w += 1
instead of:
w = w + 1

Related

Exception thrown: 'System.IndexOutOfRangeException' in VB.net

So I keep getting the error
Exception thrown: 'System.IndexOutOfRangeException'
For my array counter. I'm still learning Visual Basic but I have programming knowledge in other languages, so I'm not sure if I'm just not translating between syntax properly here, or if it's just a logic error I'm not seeing.
The arrayNumsMultiply() array is an Integer array declared with 6 values. My counter variable was also declared as an Integer previously in the program.
The following code is meant to count through the 6 numbers, check if they have two integers in them (ex: 47, so 4 and 7), and then add them together. From there, it stores it back into the array and wipes the previous value. I have a System.Console.WriteLine in the code to see if the If statement is even being initiated and it's not, but the counter console log is. Any idea on what I may be doing wrong? (The specific line where the error is being thrown is the If arrayNumsMultiply(counter).ToString.Length = 2 Then)
For counter = 0 To 5
If arrayNumsMultiply(counter).ToString.Length = 2 Then
Dim numOne As String = arrayNumsMultiply(counter).ToString().Substring(1, 1)
Dim numTwo As String = arrayNumsMultiply(counter).ToString().Substring(2, 1)
Convert.ToInt32(numOne)
Convert.ToInt32(numTwo)
Dim totalNum As Integer
totalNum = numOne + numTwo
arrayNumsMultiply(counter) = totalNum
System.Console.WriteLine("If statement for adding in an integer working")
End If
System.Console.WriteLine("Counter working")
Next counter
If the length of you string is 2, the the first character is at position 0 and the second character is at position 1. Like most things in .net this is zero based. So the correct code for these lines is...
Dim numOne As String = arrayNumsMultiply(counter).ToString().Substring(0, 1)
Dim numTwo As String = arrayNumsMultiply(counter).ToString().Substring(1, 1)

Subscript out of range error in VBA?

I am trying to keep the values in the array. There is some 604 values it retrieves. This is giving me subscript out of range error. Can anyone help?
PlCounter = 1
ReDim PlArray(1 To PlCounter)
For Each plv In fs.PickListValues
Debug.Print "entered into loop"
Set pl = plv
Debug.Print pl.Value
If Len(pl.Value) = 0 Then
Debug.Print " The length is null ..so assigining null"
ReDim Preserve PlArray(1 To PlCounter)
PlArray(PlCounter) = "NULL"
PlCounter = PlCounter + 1
Else
Debug.Print " The length is not null ..so assigining vlaues"
ReDim Preserve PlArray(1 To PlCounter)
PlArray(PlCounter) = pl.Value
PlCounter = PlCounter + 1
End If
Next plv
End If
Next v1
Debug.Print "The final value of Plcoutner is "; PlCounter
Debug.Print "The Final Value of PlArray "; PlArray(PlCounter - 1) -- This is getting out of range error
I believe that you are trying to print PlArray(PlCounter - 1) when in fact your array goes from 1 to PlCounter, so in essence the debug print is trying to print PlArray(0) which is out of range.
You could fix this by replacing this line:
Debug.Print "The Final Value of PlArray "; PlArray(PlCounter - 1)
With something like this:
If PlCounter > 1 then Debug.Print "The Final Value of PlArray "; PlArray(PlCounter - 1)
If all you are trying to get out of the array is the upper-most value (as in, the value at the upper-most bound) then just use the property meant for that:
Debug.Print "The upper bound is "; Ubound(PlArray); "with a value of "; PlArray(Ubound(PlArray))
This ensures that you get the very last index of the array, regardless of how it is defined. This will also work if there is only one item in the array.
Likewise, you could use a similar operation when using Redim:
ReDim Preserve PlArray(LBound(PlArray) To UBound(PlArray) + 1)
This will help you avoid using that counter variable which will inevitably cause issues, especially since it is only being used to resize the array.
On a separate note, you may want to consider loading your range into an array in one shot. This will be faster to loop through as well (if you want to nullify what would otherwise be Empty for null cells).:
Dim Foo as Variant
Foo = SomeWorksheet.Range("A1:A100").Value
Keep in mind this will create a 2d array with a lower bound of 1 on both dimensions. So, if you need a 1d array, you must translate the items out of this array and into your 1d array.

VBA Compile error inside if statement

If IsArray(payCsv(pay_id)) = False Then
'create tempArray
lc = 0
Debug.Print "create array"
End If
If IsArray(payCsv(pay_id)) = True Then
Debug.Print " array exists, we should be able to get ubound"
lc = UBound(payCsv(0)) - LBound(payCsv(0))
l = l + 1
End If
I am using the above code to determine whether I can use Ubound on my 2D array (i.e. if the 2nd dimension is created, get length (ubound - lbound).
However, I am getting a compile error, even though condition 2 is false, it does not recognise that the code will not be relevant.
I am testing one array and the result is if I comment out "lc = UBound(payCsv(0)) - LBound(payCsv(0))" is "create array".
If I leave this line in there, I get the error "compile error - expected array"
Is this a bug in VBA?
If you want to access the UBound of the 2nd dimension of an array, the format goes like this:
UBound(payCSV, 2)
The MSDN page on this function may be helpful.
When you access payCSV(0) as you currently are, the code assumes that you want the 1st element within the 1st dimension of the payCSV array.
Perhaps you might want to try this?
If IsArray(payCsv(pay_id)) = False Then
'create tempArray
lc = 0
Debug.Print "create array"
Else
Debug.Print " array exists, we should be able to get ubound"
lc = UBound(payCsv, 2) - LBound(payCsv, 2)
l = l + 1
End If

Excel VBA - count number of different parameters in table

I have some problems with my excel VBA code, it does not work and yes, I do not know why...
I want to add each Record number once in a collection. My code looks like this:
For i = 1 To lo.ListRows.Count
Count = 1
Do While recordList.Count >= Count
recordFound = False
If lo.ListColumns("Record").DataBodyRange.Rows(i) = recordList(Count) Then
recordFound = True
End If
If recordFound = False Then
recordList.Add (lo.ListColumns("Record").DataBodyRange.Rows(i))
End If
Count = Count + 1
Loop
Next
What it does now, it returns empty collection...
Whould be great if you could help me guys!
There is no real need to test the Collection to see if the item exists if you give it a key.
You can code something like:
On Error Resume Next
For I = 1 To lo.ListRows.Count
With lo.ListColumns("Record").DataBodyRange.Rows(I)
RecordList.Add Item:=.Value, Key:=CStr(.Value)
End With
Next I
On Error GoTo 0
Adding an item with the same key will cause the operation to be rejected. If you are concerned about other errors than the duplicate key error, you can always check the error number in the inline code and branch depending on the results.
I haven't been able to test this with the reference to lo but it works with a reference to a range
Dim objDictionary As Object
Dim dictionaryKey As Variant
Dim i As Long
Set objDictionary = CreateObject("Scripting.Dictionary")
For i = 1 To lo.ListRows
objDictionary.Item(CStr(lo.ListColumns("Record").DataBodyRange.Rows(i))) = objDictionary.Item(CStr(lo.ListColumns("Record").DataBodyRange.Rows(i))) + 1
Next i
For Each dictionaryKey In objDictionary.keys
' Do something
Next dictionaryKey
I have used a dictionary object instead of a normal collection object as it should do what you are trying to do. Because the item is incremented each time, you can also return the count of each item by using
objDictionary.item(dictionaryKey)

How to fix "Compile Error: Object Required" error?

This is my very first time with VBA. For the following code fragment:
Dim i As Integer
Set i = 0
For Each v In dictDT.Keys
Cells(10, 5 + i) = dictDT.Item(v)
i = i + 1
Next
I keep getting this error:
Compile Error: Object Required
What am I doing wrong?
Change
Set i = 0
to
i = 0
Only objects require the Set keyword. Other variable types do not.