Null Reference Error Visual Basic - can't find the issue - vb.net

I'm writing code and there is a null reference exception. I can see where it is, but I can't work out how to fix it. I'm honestly not sure why, I've been reading and re-reading my code, trying different things. I think I'm being dense or possibly have a mental block on it somehow.
The two bits of code are :
For looper = 0 To 3
Sandpit.Controls.Add(Me.QueueMembers(looper).VisRep)
Me.QueueMembers(looper).VisRep.ForeColor = Me.QueueMembers(looper).GetBackgroundColour
Select Case (Me.Direction)
Case "R"
TempPoint.X += 32
TempPoint.Y = 260
Case "U"
TempPoint.Y += 32
Case "L"
TempPoint.X -= 32
End Select
Which works for creating a queue and everything. When I try to remove anything from the queue, though, using the following code:
Public Sub RemoveDiner()
Dim TempDiner As Diner
For looper = 0 To Me.EndPointer - 1
TempDiner = QueueMembers(looper)
QueueMembers(looper) = QueueMembers(looper + 1)
Next
DrawQueue()
End Sub
It's the looper causing the problem, I think because once the item is deleted, there aren't three items in the QueueMembers array.
If someone could just give me advice on how to fix this because I'm being completely dense about it, please, I would be very grateful.
Thanks!

Related

Reverse number array multiline textboxes

basically, I want to reverse the numbers. (in the textbox there will be only 2-digit numbers)
if I have Textbox1.text:
12
2
41
71
70
I want to display in the box (Textbox1.text)
21
2
14
17
70
Function:
Public Shared Function Reverse(num As Integer) As Integer
Dim _reverse As Integer = 0
While num <> 0
_reverse *= 10
_reverse += num Mod 10
num \= 10
End While
Return _reverse
End Function
it should work, it actually works, but I don't know how to arrange it to work in all lines.
For Each lines In TextBox1.Lines
Dim rev = Reverse(lines)
lines.Replace(lines, rev)
Next
This is a perfect example of what happens when people try to write code without knowing what the code is supposed to. What the code is supposed to do is not just the end result but the steps to get there. If you don't know what the steps are then you shouldn't be writing any code because it's unlikely that what you write will do anything useful. Code is simply an implementation of logic so you should be getting the logic down first. It doesn't take any programming experience to work out the logic because we could all do this if it was a manual process and that would be the same logic.
So, what are the steps involved?
Get the lines of the text.
Loop over the lines.
Reverse the current line.
Replace the original line with the result of reversing.
Replace the text with the complete results.
If you actually consider each of those steps, it should be obvious that you cannot use a For Each loop because that will only let you get data out of a list, not put data into it. That would make it obvious that a For loop is the right choice, because will let you get data out and put it in. Now you can write code that actually does something useful.
Dim lines = TextBox1.Lines
For i = 0 To lines.GetUpperBound(0)
Dim line = lines(i)
Dim number = CInt(line)
Dim result = Reverse(number)
lines(i) = result.ToString()
Next
TextBox1.Lines = lines
Simple stuff but, again, if you don't know what the code has to actually do, writing code to do it is a challenge. Always break the problem down into smaller parts first, so you can work on each part individually, and always work out the logic you're trying to implement - and test that logic manually - before trying to write code to implement it.

Microsoft Access VBA

The Error States:
Run-time error '94'
Invalid use of Null
Options to: (End) (Debug) (Help)
I hit Debug
Microsoft Visual Basic for Applications opens window for
(Calculate Functions Code)
(Issue Below)
'Add Leap Year determination
Dim blnIsLeapYear As Boolean
Dim intYear As Integer
blnIsLeapYear = False
intYear = YY
If (intYear Mod 4 = 0) Then
blnIsLeapYear = True
If (intYear Mod 100 = 0) Then
If (intYear Mod 400 <> 0) Then
blnIsLeapYear = False
IntYear = YY is highlighted in YELLOW. I have no idea how to fix the issue.
You are missing the "End if" in your code.
Remember the if structure is:
If something then
Do what you need
End if.
for example:
If (intYear Mod 4 = 0) Then
blnIsLeapYear = True
End if
Another problem is that you are assigning the YY to intYear in intYear = YY , but you never created of populated the YY.
It is very important to put
Option Explicit at the top of each module.
This is flag whenever you use a variable which hasn't been declared.
Like you've done, it's a good idea to have at least one capital letter in every variable.
That way, when you enter line, you'll know immediately if you've spell each variable correctly as soon as you leave that line.
I always name globals in all capitals - like Public Dim YEARPAST as Long
or Const YEARPAST as Long = 1
Then I know something is a global
I know a lot of coders think globals are a bad idea but they work for me, either at the project level, or in a particular module so I don't have to pass values in variables all the time. Also, a nice way to communicate information across the project or procedures in a module.

Problem with WorksheetFunction.Norm_S_Inv()

I am trying to make a modelisation of Monte-Carlo for 5000 trials.
I seem to have a weird problem with
g = WorksheetFunction.Norm_S_Inv(Rnd())
During the functioning of the loop (of the 5000 trials), at first it is working but then an error message occurs:
Run-time error "1004":
Method 'Norm_S_Inv' of object 'WorksheetFunction' failed
I have checked on many VBA sites and I don't seem to find a solution.
I also tested with
Application.WorksheetFunction.Norm_S_Inv(Rnd())
with WorksheetFunction.Norm_S_Inv(Rnd())
with WorksheetFunction.Norm.S.Inv
with Application.WorksheetFunction.Norm.S.Inv(Rnd())
with WorksheetFunction.NormSInv
Thank you in advance,
It happens when your Rnd() returns a value of 0 or 1, which is of course an acceptable value for the Rnd() function but it is not as an input of the Norm_S_Inv().
I can reproduce that easily on my computer (my Excel is in Italian, actually I get the 1004 code but the text on my side rather says "Cannot find property Norm_S_Inv for the class WorksheetFunction):
g = WorksheetFunction.Norm_S_Inv(0.14)
Debug.Print g
>>> -1.08031934081496
g = WorksheetFunction.Norm_S_Inv(0) 'or g = WorksheetFunction.Norm_S_Inv(1)
>>>
In order to avoid that, make sure you don't get 0 or 1 as inputs of your function:
myRand = Rnd()
Do Until (myRand <> 0 And myRand <> 1)
myRand = Rnd()
Loop
g = WorksheetFunction.Norm_S_Inv(myRand)
Personal note: this seems a pretty bad error handling done for this function, the error message is not at all clear and I understand your frustration in finding the root cause.

VBA Excel Break Points and Stop do not work

Any idea why inserting break points and stop no longer stops my vba code from running?
The code runs ok all the way to the end (I tested it) but ignores break points and Stop.
Also step into just makes the code run in it's entirety, ignoring break points and stops.
When I close the workbook where the issue seems to originate from the same issue occurs in other macro workbooks.
if I completely close excel and re-open it with a normally working macro workbook the issue doesn't occur until I re-open the problem work book.
I added breakpoints on:
TotP1 = 0
of the following code:
Option Explicit
Private Country As String
Private Measure As String
Private P1 As String
Private P2 As String
Private TotP1 As Double
Private TotP2 As Double
Sub VennDisplayIt()
Dim SI() As String
Dim SICount As Integer
Dim x As Integer
Dim OSh As Worksheet
Dim BrandListBox As Object
Dim VennGroup As Shape
TotP1 = 0
TotP2 = 0
Set OSh = ThisWorkbook.Sheets("Venn")
Set BrandListBox = OSh.OLEObjects("BrandListBox").Object
ReDim SI(2, 0)
For x = 0 To BrandListBox.ListCount - 1
If BrandListBox.Selected(x) = True Then
'If UBound(SI) < 4 Then
ReDim Preserve SI(2, UBound(SI, 2) + 1)
SI(1, UBound(SI, 2)) = BrandListBox.List(x)
SI(2, UBound(SI, 2)) = x + 1
'End If
End If
Next x
If UBound(SI, 2) < 2 Then
BrandListBox.Selected(BrandListBox.ListIndex) = True
Exit Sub
ElseIf UBound(SI, 2) > 4 Then
BrandListBox.Selected(BrandListBox.ListIndex) = False
Exit Sub
End If
For x = 1 To UBound(SI, 2)
OSh.Range("o8").Offset(x, 0).Value = SI(1, x)
OSh.Range("o8").Offset(x + 5, 0).Value = SI(1, x)
Next x
For x = UBound(SI, 2) + 1 To 4
OSh.Range("o8").Offset(x, 0).Value = ""
OSh.Range("o8").Offset(x + 5, 0).Value = ""
Next x
SICount = UBound(SI, 2)
For x = 1 To OSh.Shapes.Count
If Right(OSh.Shapes(x).Name, 5) = "Group" Then
If LCase(OSh.Shapes(x).Name) = SICount & "waygroup" Then
Set VennGroup = OSh.Shapes(x)
OSh.Shapes(x).Visible = True
Else
OSh.Shapes(x).Visible = False
End If
End If
Next x
For x = 1 To SICount
VennGroup.GroupItems.Item(SICount & "WayBrand" & x).DrawingObject.Text = SI(1, x)
Next x
Country = ThisWorkbook.Sheets("Venn").Range("D4").Value
Measure = ThisWorkbook.Sheets("Venn").Range("E32").Value
P2 = ThisWorkbook.Sheets("Venn").Range("E31").Value
P1 = ThisWorkbook.Sheets("Selections").Range("B5").Value
End Sub
I've never heard of Stop not working, but I've heard about and experienced the breakpoint thing many times. When you compile VBA, it creates a p-code, which is used by the interpreter. You have the VBA syntax layer that you can see and the p-code layer that you can't see. When breakpoints stop working, it's because the p-code was corrupted. I don't know how or why it happened, but it did.
The fix is to export, remove, and reimport all of your modules. Exporting them creates a .bas file (plain text, really). When you re-import, the p-code is regenerated from scratch. If you have more than a couple of modules, get CodeCleaner (free add-in) and it will export and reimport automatically.
If one of the settings is unchecked then breakpoints will not work. "File/options/Current database/Application options/use access special keys" should be checked
Just to 'second' Tibo's comment: I had a problem where I had a form with about 5 different subroutines. One of them (attached to a button event) would not stop when I set a breakpoint. in 10 years of VBA writing, I've never seen that happen. Interestingly, breakpoints worked on all of the other subroutines in that form. After much head-scratching and searching, I came upon this post and Tibo's comment. I added a "Stop" command to the affected subroutine, ran the procedure (it stopped as it should have) and then breakpoints began working again! Hope this helps someone in the future.
If the breakpoints are in your code, then the code should stop running as soon as it hits that line. Possible causes of your problem:
a) The code never gets to the Breakpoint.
Seems highly unlikely seeing as you're breaking on the first line of your code. Maybe step through the sub (F8) just to check it's running as it should.
b) Your breakpoints have been wiped. Any line with a breakpoint should display as highlighted in red on your IDE. Your breakpoints can easily be wiped through, e.g. closing and opening the workbook (a screenshot would be really useful).
c) your workbook is broken in some way. It would be unlikely to break something as fundamental as stopping at breakpoints and still function normally. Are you sure your code is actually running?
Just sharing a funny thing which happened to me in case it helps someone. The mistake I did was that I simply took someone's method code meant for workbook open event and pasted it on Sheet1 excel object code area. So there was no possibility of Workbook_Open method getting fired ever.
Private Sub Workbook_Open()
Stop
On Error Resume Next
Call ActiveSheet.Worksheet_Activate
On Error GoTo 0
End Sub
What I was supposed to do is paste this method after double clicking ThisWorkbook node under Microsoft Excel Objects in Project pane as shown below:
Note: Side effect of copy-pasting others code can be freaky at times.
a) Double check that your breakpoints got disabled or not.
b) Double check that you added a conditional breakpoint or not
c) If you run your macro using C# code (using, the _Run2 command), breakpoints and stop doesn't work sometimes.
I have the problems as described above:
Stop and Breakpoints not working
Single step F8 worked, but code was not highlighted in yellow
Closing VBA editor did not help
My remedy: close VBA editor again, save Excel-file, open editor, back to normal
I've never faced this problem for years. Today for the first time I started using watch expressions with stopping when true.
This happens to me once in a while and the following solves the problem for me every time:
Create a Sub with only the command Stop in it. Run it. Then try your routine, the breakpoints and Stop commands should now work correctly.
Make sure that you do not have a named Range that matches the name of the Function or Subroutine you are calling. This will look like the Function or Subroutine is failing, but it is actually failing before the routine is ever called with an 'invalid cell reference'.
I had this problem as well. My solution was put an error in the code and run it. After I cleared the error the breakpoints started working again. That was weird.
I been writing code in VBA for many years but today I came across this problem for the first time. None of the solutions I found on the web worked but here's something simply you can use instead of Stop:
ErrCatch = 1 / 0
Still doesn't solve the breakpoints not working though...
I went int my vba code, added an enter (new blank line), then ran it again.
Voila! It ran the code and stopped at the breakpoint!
Not just me then! On a few occasions the yellow hi-lite stops a few lines beyond the breakpoint! I guess the code is running so fast it can't stop in time. :) As suggested above, I find adding "stops" here and there and also exporting & re-importing helps too.

Endif must be preceded by a matching if

I have a piece of vb.net code that I wrote. It's a for loop with two embedded if statements, and the compiler is telling me that each elseif and endif must be preceded by a matching if.
This is my second day of working with vb.net ever, and the only programming experience I have is writing .bat files, so this could be something really stupid. But I cannot figure out why I'm getting these errors, and if you all would be willing to help me out, I would greatly appreciate it!
For Each computer In compArray
If compArray(I) <> Computers.GetKey(I) Then notpresentList.Add(Computers.GetKey(I))
Else
If Computers.GetByIndex(I) = 0 Then disabledList.Add(Computers.GetKey(I))
Elseif Computers.GetByIndex(I)=1 Then enabledList.Add(Computers.GetKey(I))
Elseif Computers.GetByIndex(I)=2 Then unknownList.Add(Computers.GetKey(I))
End if
End if
I += 1
Next
The context for this: I am trying to write a piece of code that will confirm the presence of bitlocker. I wrote in VBScript something that will check whether bitlocker is enabled and then send an email. This piece of code is a part of a program which would retrieve those emails, compare them to a list of computers, and then produce a digest email which states which computers are absent, have bitlocker enabled, disabled, or in an unknown state.
I'm sure there's another and better way to do this, but as I said, I'm fairly new at this, and we need to have this done for legal reasons.
Thanks again!
EDIT: If you need more info, please ask me!
I would use the inline syntax in VB.NETonly with short and simple conditions. Otherwise it makes the code less readable and more error-prone.
Try this:
For Each computer In compArray
If compArray(i) <> Computers.GetKey(i) Then
notpresentList.Add(Computers.GetKey(i))
Else
Dim comp = Computers.GetByIndex(i)
If comp = 0 Then
disabledList.Add(Computers.GetKey(i))
ElseIf comp = 1 Then
enabledList.Add(Computers.GetKey(i))
ElseIf comp = 2 Then
unknownList.Add(Computers.GetKey(i))
Else ' added this to show you that this case is not covered yet
Throw New NotSupportedException
End If
End If
i += 1
Next
Your If…Then lines need to be broken up. Move everything after Then to the next lines and you should be good.
If compArray(I) <> Computers.GetKey(I) Then notpresentList.Add(Computers.GetKey(I))
If…Then statements on one line are self-contained, are not followed with a terminating End If, and may not use ElseIf.
Your confusion is in the VB.NET syntax for If statements. VB.NET allows two different formats which each have different syntax rules: Single-line If statements, and Multi-line If blocks.
A single-line If statement looks like this (notice that there is no End If):
If x Then y = 1
A multi-line If block looks like this:
If x Then
y = 1
End If
When you put code on the same line, after the Then, it assumes that you intend it to be a single-line If statement. Single-line If statements cannot include ElseIf, nor Else conditions. They can only be used for simple conditions. Therefore, to make your code work properly, you need to format it as a multi-line If block by putting the conditional code on the following line, like this:
For Each computer In compArray
If compArray(I) <> Computers.GetKey(I) Then
notpresentList.Add(Computers.GetKey(I))
Else
If Computers.GetByIndex(I) = 0 Then
disabledList.Add(Computers.GetKey(I))
Elseif Computers.GetByIndex(I)=1 Then
enabledList.Add(Computers.GetKey(I))
Elseif Computers.GetByIndex(I)=2 Then
unknownList.Add(Computers.GetKey(I))
End if
End if
I += 1
Next
For more information on the syntax, take a look at the MSDN page on the If statement.
Single line If's should all start with just If:
i.e.
If Computers.GetByIndex(I) = 0 Then disabledList.Add(Computers.GetKey(I))
If Computers.GetByIndex(I) = 1 Then enabledList.Add(Computers.GetKey(I))
If Computers.GetByIndex(I) = 2 Then unknownList.Add(Computers.GetKey(I))
You can also use Select Case to make it more readable, i.e.
Select Case Computers.GetByIndex(I)
Case 0
disabledList.Add(Computers.GetKey(I))
Case 1
enabledList.Add(Computers.GetKey(I))
Case 2
unknownList.Add(Computers.GetKey(I))
Case Else
' Some sort of default action can go here, useful for error catching/prevention
End Select