why would a boolean revert to an original value? - vba

I know this might be a more of a general question, but I've looked at my code a 100 times and am not sure what's wrong. I set a global flag so that it can be used in different forms of my application.
Dim OverPopulated as Boolean
I have a function where I first set it to FALSE, and after it goes through some validating it gets set to TRUE.
Now i do a bunch of stuff, go through different forms, and the value stays correct the entire time. Basically I need this value for another form, so when I check
if OverPopulated = false then
MsgBox "You Can't do this and that"
exit sub
End if
Then all of the sudden it gets set to FALSE. I've went through every instance of OVERPOPULATED in my application and put a break point to it to make sure that nowhere do i set it to FALSE, except for the one time I set it to FALSE before my validation.
I only have it in 2 other forms in my applications. There is one place where the flag is being run twice through the same statement (just like the one above). The first time it goes through, the value is correct, then it goes through again and the value is set to FALSE.
Any ideas? if this is too vague, please let me know, I'll try to edit it.
EDIT: I deleted a lot of the code but here's how it looks.....
Dim OverPopulated as Boolean
' modular level
Private Sub ValidatePopulation()
Dim admDate as date
OverPopulated = False
admDate = Format(Now(), "mm/dd/yyyy")
Select Case revPURP
Case 0, 1, 2
'Check make sure these fields
'some if statements, checking, validation
Case Else ' no need to do a
End Select
OverPopulated = True 'I MAKE SURE IT GETS HERE and is set to TRUE!!!
End sub
Now, in other functions I used it like this...
If OverPopulated = False Then
If optStat (0).Value = True Or optStat (1).Value = True Then
MsgBox "You are not able to do this”, vbCritical, "Incorrect review status...."
TabPop.Tab = 6
End If
Exit sub
Else
'Proceed with SAVE
End If
So I have this. and I have another statement just like this somewhere else. This one gets hit twice. The first time I go through it line by line and it's FALSE, then the 2nd time around the value is TRUE.

It looks like for some reason the value was getting reset to FALSE. I took out the Dim OverPopulated as Boolean from my form code, and placed it in a GLOBAL module where all the other globals are stored. This seems to have fixed the issue of the value remaining the same while I'm manuevering in the application. Thank you for all your comments.
Global OverPopulated as Boolean

Related

Changing a CheckBox's Font Attribute "Strikethrough" from a specific module does not work

Using VBA (Excel 365 (16.0.12527.20880), German) I'm trying to set the strikethrough property of a checkbox (Checkbox1) caption to False in accordance to the Office VBA reference this should work.
The following code is placed in a Module1 (simplified) and changes the strikethrough-value of UserForm1.Checkbox1 (UserForm1 and Checkbox1 is static, created via the VBA-Editor, not via code during runtime).
Sub ChangeCheckBox()
UserForm1.CheckBox1.Caption = "Test" 'this triggers the Init-Procedure, which only sets the Height and Width of the UserForm. This shouldn't effect the problem, but I'm mentioning it here so it's clear that the form has been initialized. But if I leave it out, it's the same problem.
'Pre-Test - works fine
'Check initial value
Debug.Print UserForm1.CheckBox1.Font.Strikethrough 'returns false (as it should)
'Write value and check it
UserForm1.CheckBox1.Font.Strikethrough = False
Debug.Print UserForm1.CheckBox1.Font.Strikethrough 'returns false (as it should)
'Write value and check it again
UserForm1.CheckBox1.Font.Strikethrough = False
Debug.Print UserForm1.CheckBox1.Font.Strikethrough 'returns false (as it should)
'This next line seeems to cause the post-test failure
tmpString = ThisWorkbook.Worksheets("Sheet1").Cells(tmpIndex, tmpColumn).Value
Debug.Print tmpString 'returns the correct value
'Post-Test - fails!!!
'Check initial value
Debug.Print UserForm1.CheckBox1.Font.Strikethrough 'returns false (as it should)
'Write value and check it
UserForm1.CheckBox1.Font.Strikethrough = False
Debug.Print UserForm1.CheckBox1.Font.Strikethrough 'returns true (should still be false)
'Write value and check it again
UserForm1.CheckBox1.Font.Strikethrough = False
Debug.Print UserForm1.CheckBox1.Font.Strikethrough 'returns true (definitely should return false now)
End Sub
In my case, for some reason, the command sets the box to True instead of False. So far I pinpointed the problem to a specific line of code. The "Pre-Test" succeeds, the "Post-Test" fails (everything else works fine). Note, I'm using debug mode via step by step, no other code is executed "in-between".
The problem persists if I create a different Form and try the same thing there. The original procedures are several hundred lines of code, but I created the Testprocedure above and the problem persists. I can also reproduce it by creating a new Excel file from scratch with just one Sheet, one Userform/Checkbox, and one Module containing the test procedure.
So, why the hell does tmpString = ThisWorkbook.Worksheets("Sheetname").Cells(tmpIndex, tmpColumn).Value cause the "Post-Test" to fail?
Note: This error can not be reproduced on all machines, I tried it on a different machine. There, I can not reproduce the error.
I cannot reproduce the issue and I've tried on 3 different machines.
However, I remember seeing a similar issue about 7 years ago and I managed to work around it by first checking if I need to change the value of the font property.
Try replacing all occurences of this:
UserForm1.CheckBox1.Font.Strikethrough = False
with this:
If UserForm1.CheckBox1.Font.Strikethrough Then UserForm1.CheckBox1.Font.Strikethrough = False
This basically sets the .Font.Strikethrough property to False only if it is already True because otherwise it is False (obviously) and if there is any bug in the setter of that property then this skips the bug.
Unrelated to your question but it's not a good idea to use the default instance of a Userform like you're doing here with Userform1.Checkbox.... I recommend you read this article written by #MathieuGuindon back in 2017.
Try using index for your worksheet instead of the name.
Its a funny thing to happen in a programming language.
tmpString = ThisWorkbook.Worksheets(1).Cells(tmpIndex, tmpColumn).Value
Debug.Print tmpString
It worked for me and I think because the polymorphic functions in VBA made without debugging! because nothing else could cause this kind of behavior!
I've managed to reproduce the issue the same way it occured to you.
The root cause here is that you are not explicitly UNLOADING the form after you close it, which means that all modifications that you made to it while open get retained in memory.
For example using your code, shows the checkbox with strikethrough even when running it 2nd time. Which means it's retained in memory.
So to fix this, simply add Unload UserForm1 in your procedure after running the code.
While this approach works in resetting the checkbox (which I assume is your ultimate goal here), it still returns true for those last 2 checks for some reason. To workaround that as well (though it could be unnecessary if you achieve your goal), then simply use #Cristian Buse's if/then solution.

MS Access refresh form and keep position on screen [duplicate]

This should be an easy one. This form is filtered by [Dismissed] = "N". When the user clicks the "Dismiss" button, the [Dismissed] field changes to "Y". After the requery, the form should then return to the same row where the user was previously at.
Private Sub DismissButton_Click()
Me!Dismissed = "Y"
MsgBox "Dismissed!", vbOKOnly
Dim GoBackToThisRecord As Integer
GobacktothisRecord = Me.CurrentRecord
Me.Requery
Set Me.CurrentRecord=GoBackToThisRecord
End Sub
However, even though the built-in help files say that CurrentRecord is a read/write property, I get an "Invalid use of property" error message on this last line.
After setting the [Dismiss]="Y", and requerying the form, how do I get the user back to his/her previous location in the form?
I don't understand how your solution can work if the form is filtered to a value that the edited record no longer matches -- if you're filtered on [Dismissed] = "N" then changing the current record's Dismissed field to Y should cause the requeried form to exclude the record you've just updated.
That aside, I would never do it the way you've done it, as Me.CurrentRecord returns a number representing the position in the record. Since a requery can cause the number of records to change (e.g., somebody else edits or adds or deletes a record causing it to be included/excluded from the form's recordset) and the position of the sought-for record to change, I would use the PK instead.
Dim lngPK as Long
lngPK = Me!MyPKID
Me.Requery
With Me.RecordsetClone
.FindFirst "[MyPKID]=" & lngPK
If Not .NoMatch Then
If Me.Dirty Then
Me.Dirty = False
End If
Me.Bookmark = .Bookmark
End If
End With
That won't deal with the filter issue, but I leave that aside, since it didn't seem to be the issue that I thought it would be from the description of the original problem.
Nevermind. Fixed it myself. The last line is now:
Me.Recordset.Move GoBackToThisRecord
The right way to move to the previous record, whether it is a new one or not, is
Me.Recordset.Move GoBackToThisRecord -1
I use this function:
Public Sub RequeryFormAndKeepCurrentlySelectedRecord(f As Form)
Dim Position As Long
Position = f.CurrentRecord
f.Requery
If Position > 1 Then
f.Recordset.move Position - 1
End If
End Sub

Continue Through An If Statement If False

I'm trying to create a simple ignore list option for my program. When a sub runs, I want it to not execute some code if a user is on the list and a checkbox is checked.
I have tried this:
If Not My.Settings.IgnoredNames.Contains(PartnerDisplayName) AndAlso chkIgnore.Checked = False) Then
'Do something...
End If
This works, except even when the check box is checked by itself the if statement doesn't continue. I don't have a clue how to rewrite it.
This will not work either and I don't really know why. The sub triggers on an certain API event, and exiting it like so still lets the real code go through.
If My.Settings.IgnoredNames.Contains(ParterDisplayName) And chkIgnore.Checked = True Then Exit Sub
'Do something...
Instead of using Nots and creating messy logic, just invert your If statement and short circuit out if you hit the condition where you don't want to run the code:
If My.Settings.IgnoredNames.Contains(PartnerDisplayName) AndAlso chkIgnore.Checked = True Then
Return
End If
' Do your other logic here.

Suppress MsgBox from another Subroutine in VBA

I have a VBA sub that makes a call to a sub that was written by someone else. occasionally, the other sub opens a MsgBox with an OK button. The other sub takes a long time to run, and I am calling it hundreds of times, so I want to be able to run this overnight. Unfortunately, I can't figure out a way to automatically click OK on the MsgBox.
I have tried
Application.DisplayAlerts = False
but this doesn't suppress message boxes.
Is there any way to do this?
Thanks
One way to do this is slightly modifying the code of the original sub. You will need to have the necessary permissions tough...
Modify the header of the original sub by throwing in an extra optinal parameter at the end setting the default value to True. This will result in something like Sub OriginalSubName(original set of parameters, Optional ShowMessages = True)
At the point where the msgbox is called, modify the code this way:
If showMessages = True Then 'The = True part is important here - see below.
showMessages is a Variant type
'The original statement that calls the msgBox
End If
Leave the rest of the code of the original sub unchanged
Modify the line where you call the original sub by throwing in False as an extra parameter. This results in OriginalSubNameyour set of parameters, False. This way you don't suppress the dialog box by default, but you do when you use it in your sub.
Wonder why I use an optional Variant type parameter?
The optional part: this prevents other existing subs from crashing when they call the modified sub
The Variant type part: optional parameters are always Variant type. That's also why you need to use If showMessages = True Then instead of just If showMessages Then.

Object reference not set to an instance of an object (Completely broken?) in vb.net

I know, I know, I could have used a for loop, dont tell me anything about that. Please, help!
Private Function LoadSaved() ''//Loads saved clippings if the user wants us to
Dim ZomgSavedClips As StringCollection
If IsDBNull(My.Settings.SavedClips) = False Then ''//If it is null this would return a rather ugly error. Dont want that do we?
ZomgSavedClips = My.Settings.SavedClips ''//ZomgSavedClips name was a joke, I just felt like it.
ZomgSavedClips.Add(" ") ''//This line ought to fix the error, but doesnt
i = 0
While i < ZomgSavedClips.Count ''//This is where the error occurs
ClipListings.Rows.Add(ZomgSavedClips(i))
i = i + 1 ''//First time I wrote this function I forgot this line. Crashed mah comp. Fail.
End While
End If
End Function
The line While i < ZomgSavedClips.Count is bugging, I know that the .count should return null but I even added a blank piece of text just to stop that. Whats up with this? Should I add actual text?
SavedClips is null no? If it is null it could pass the test IsDBNull beacuse the both are not the same
Obviously, My.Settings.SavedClips is still set to Nothing.
SavedClips is regular 'ole null (nothing in VB). Include a check for "My.Settings.SavedClips is nothing". If that evaluates to true then just leave the function.
I even added a blank piece of text just to stop that.
All you did was move where the error happens. You can't call .Add() on a null/Nothing object.
'''<summary>Loads saved clippings if the user wants us to</summary>'
Private Sub LoadSaved() ''//Loads saved clippings if the user wants us to
''//Load saved clips into memory
Dim ZomgSavedClips As StringCollection = My.Settings.SavedClips
If ZomgSavedClips Is Nothing Then ZomgSavedClips = New StringCollection()
''//Apply loaded clips to visible listings
Dim i As Integer
While i < ZomgSavedClips.Count ''
ClipListings.Rows.Add(ZomgSavedClips(i))
i += 1
End While
End Sub
Some notes on this code:
Don't use Function when you mean Sub
Since you'll be selling this code to others, you want to use xml comments at the top so that Visual Studio can give better intellisense helps.
IsDBNull() doesn't do what you think it does.
Yes, you should use a for loop, but since you already commented on that I left the while loop alone with the assumption that there's more code you didn't show us.