ACCESS : VBA Code Button Visibility not working - ms-access

I have a problem in hiding my buttons and not working mostly is when the button itself was clicked, it supposed to be hidden.
I have a code below from one of my buttons but most of the button visibility codes are not working. I tried to add:
DoEvents
but still don't work. I don't know what the problem is. Some Enable properties were working but some are not.
Private Sub cmdSave_Click()
If MsgBox("Are you sure to save record?", vbYesNo, "Save Record") = vbYes Then
DoEvents
imgPic.Enabled = False
txtLRN.Enabled = False
txtLN.Enabled = False
txtFN.Enabled = False
txtMN.Enabled = False
txtS.Enabled = False
txtA.Enabled = False
txtBD.Enabled = False
txtBP.Enabled = False
txtMT.Enabled = False
txtIP.Enabled = False
txtRG.Enabled = False
txtAH.Enabled = False
txtAB.Enabled = False
txtAM.Enabled = False
txtAP.Enabled = False
txtF.Enabled = False
txtM.Enabled = False
txtGN.Enabled = False
txtGR.Enabled = False
txtCN.Enabled = False
txtR.Enabled = False
DoEvents
cmdSearch.Visible = True
cmdFirst.Visible = True
cmdPrev.Visible = True
cmdNext.Visible = True
cmdNext.Visible = True
cmdLast.Visible = True
cmdNew.Visible = True
cmdDelete.Visible = True
cmdEdit.Visible = True
DoEvents
cmdSave.Visible = False
cmdCancel.Visible = False
DoEvents
End if
End Sub

This simplified version of your procedure will trigger error #2165, "You can't hide a control that has the focus."
Private Sub cmdSave_Click()
Me.cmdSave.Visible = False
End Sub
During cmdSave_Click, cmdSave has focus, so you can't hide it without first moving focus to another unhidden control. This version will avoid that error:
Private Sub cmdSave_Click()
Me.cmdSearch.Visible = True
Me.cmdSearch.SetFocus
Me.cmdSave.Visible = False
End Sub

In similar cases, I've found that you need to specify the form reference ("Me.").
So try (for example)
Me.cmdCancel.Visible = True
In other words specify "Me." in front of the control name.

Related

Download data from dynamic button with VBA

I have some code than download CSV/HTML data from webpages without any problem. The code is something similar to this:
With ActiveSheet.QueryTables.Add(Connection:="URL;" & conexion, Destination:=Range("A1"))
.Name = "FunctionRollupMTO"
.FieldNames = True
.RowNumbers = False
.FillAdjacentFormulas = False
.PreserveFormatting = True
.RefreshOnFileOpen = False
.BackgroundQuery = True
.RefreshStyle = xlOverwriteCells
.SavePassword = False
.SaveData = True
.AdjustColumnWidth = True
.RefreshPeriod = 0
.WebFormatting = xlWebFormattingNone
.WebPreFormattedTextToColumns = True
.WebConsecutiveDelimitersAsOne = True
.WebSingleBlockTextImport = False
.WebDisableDateRecognition = False
.WebDisableRedirections = False
.Refresh BackgroundQuery:=False
End With
The problem is than the webpage (originally in the variable conexion) is beeing updated and now the data is different. For downloading the data, there is a button for "Download CSV" but the link for that button is not always the same (the URL is generated every time the user press the button).
There is a way to emulate VBA to press that button? Or maybe a different way of connect to that webpage? I've been trying MSXML2 but sincerely I don't really understand its way of work.
Thanks!

Three Options - Enabling/Disabling based on input and record value

I have a form where (among other things) there are three options which are intended to be exclusive.
optDealerPay
optCustomerPay
optNoTradeIn
I want only one to be selected at a time, but when I originally designed this, I made these into three separate table columns instead of one and using an option group. Mostly because of the output I'm wanting on a report I'm working on, too. Anyway, when one is selected, the other two go Enabled = False. The issue I'm having is when the form loads (actually using Form_Current() to ensure the record is loaded prior to "checking"), the form will disable one of the two options that are unselected, but not the other one. Here is a picture:
And here is the code I'm using:
Private Sub Form_Current()
If Me.optDealerPay Then
Me.optCustomerPay.Enabled = False
Me.optNoTradeIn.Enabled = False
Else
Me.optCustomerPay.Enabled = True
Me.optNoTradeIn.Enabled = True
End If
If Me.optCustomerPay Then
Me.optDealerPay.Enabled = False
Me.optNoTradeIn.Enabled = False
Else
Me.optDealerPay.Enabled = True
Me.optNoTradeIn.Enabled = True
End If
If Me.optNoTradeIn Then
Me.optDealerPay.Enabled = False
Me.optCustomerPay.Enabled = False
Else
Me.optDealerPay.Enabled = True
Me.optCustomerPay.Enabled = True
End If
End Sub
What's a better method to accomplish this outside of redesigning the table structure, which I'm really trying to avoid if possible. Similar code is used with the AfterUpdate() procedure on each of the three options.
Your code will execute every if statement one by one - that is some kind of mess. Make all radiobuttons enabled in design mode and try this code:
Private Sub Form_Current()
If Me.optDealerPay Then
Me.optCustomerPay.Enabled = False
Me.optNoTradeIn.Enabled = False
ElseIf Me.optCustomerPay Then
Me.optDealerPay.Enabled = False
Me.optNoTradeIn.Enabled = False
ElseIf Me.optNoTradeIn Then
Me.optDealerPay.Enabled = False
Me.optCustomerPay.Enabled = False
Else
' Maybe you should do something if none of the options is true
End If
End Sub
Your current code could essentially be reduced to:
Private Sub Form_Current()
optDealerPay.Enabled = Nz(optDealerPay, 0)
optCustomerPay.Enabled = Nz(optCustomerPay, 0)
optNoTradeIn.Enabled = Nz(optNoTradeIn, 0)
End Sub
That is, if a radio button is null or unchecked, then it is disabled; else it is enabled.
However, although this is the behaviour that you have requested, I'm not sure that this is desirable, as once the user has select an option they cannot change it.

MS Access Form locked for edit - Added unlock button but can't add New Record

I've got a MS Access form with a sub-form which I want to be read-only for existing records to prevent accidental changes. I've done this by putting simple code on both forms:
Private Sub Form_Current()
Me.AllowEdits = False
Me.AllowDeletions = False
Me.AllowAdditions = False
End Sub
I also added a button that changes the form to allow edits:
Private Sub Command110_Click()
Me.AllowEdits = True
Me.AllowDeletions = True
Me.AllowAdditions = True
End Sub
So I can then edit the form. However I have a button on the parent form to create a new record. I used the standard button function builder "Record Operations -> Add New Record" to create this button. But when I try to use it the error says: Error - You Can't Go To The Specified Record.
So I created a new button with this code:
Private Sub NewClientButton_Click()
Me.AllowEdits = True
Me.AllowDeletions = True
Me.AllowAdditions = True
DoCmd.GoToRecord , , acNewRec
End Sub
Thinking that would solve it but I still get an error: Runtime Error 2105 You can't Go To Specified Record.
The code on my form in totality looks like this:
Private Sub Command110_Click()
Me.AllowEdits = True
Me.AllowDeletions = True
Me.AllowAdditions = True
End Sub
Private Sub Form_Current()
Me.AllowEdits = False
Me.AllowDeletions = False
Me.AllowAdditions = False
End Sub
Private Sub NewClientButton_Click()
Me.AllowEdits = True
Me.AllowDeletions = True
Me.AllowAdditions = True
DoCmd.GoToRecord , , acNewRec
End Sub
Is it just the ordering of my code subs that is the problem or something else?
Thanks.

VBA Selection.InlineShapes.AddPicture keeps pasting on initial document

The below code is part of a program that populates a word document from an access database.
This part of the code adds a picture with the user's signature at the bookmark location 'Signature'. For some reason it works the first attempt, but the nex time it runs it pastes at the initial document's bookmark location and not the new document.
appword.ActiveDocument.Bookmarks("Signature").Select
Selection.Find.ClearFormatting
With Selection.Find
.Text = ""
.Replacement.Text = ""
.Forward = True
.Wrap = wdFindContinue
.Format = False
.MatchCase = False
.MatchWholeWord = False
.MatchWildcards = False
.MatchSoundsLike = False
.MatchAllWordForms = False
End With
Selection.InlineShapes.AddPicture FileName:= _
SASignaturePath, _
LinkToFile:=False, SaveWithDocument:=True
I've attempted to use a few other selection commands like:
Selection.Goto What:=wdGoToBookmark, Name:="Signature"
and
objWork.ActiveDocument.Bookmarks("Signature").Range.Select
with no luck.
Edit: Adding additional info as requested.
The entire function pulls some global variables from access and autopopulates a word document with them. The global variable 'SASignaturePath' has the file location of the signature image.
Below is the entire function being called when the user presses the 'create cost letter' button.
Function fillCostLetter()
Dim appword As Word.Application
Dim doc As Word.Document
Dim Path As String
TodayDate = Format(Now(), "mmmm dd, yyyy")
On Error Resume Next
Error.Clear
Set appword = GetObject(, "word.application")
If Err.Number <> 0 Then
Set appword = New Word.Application
appword.Visible = True
End If
Path = "Z:\DocFolder\ServiceAssociateToolBox\CostLetterTestStage.docx"
Set doc = appword.Documents.Open(Path, , True)
With doc
.FormFields("Date").Result = TodayDate
.FormFields("BillName").Result = BillName
.FormFields("BillAmmount").Result = BillAmmount
.FormFields("BillAddress").Result = BillAddress
.FormFields("BillAmmount").Result = BillAmmount
.FormFields("BillCity").Result = BillCity
.FormFields("BillState").Result = BillState
.FormFields("BillZip").Result = BillZip
.FormFields("SiteZip").Result = SiteZip
.FormFields("SiteState").Result = SiteState
.FormFields("SiteCity").Result = SiteCity
.FormFields("SiteStreetType").Result = SiteStreetType
.FormFields("SiteStreetName").Result = SiteStreetName
.FormFields("SiteStreetNo").Result = SiteStreetNo
.FormFields("BillName2").Result = BillName
.FormFields("WorkRequest").Result = WR_NO
.FormFields("CustName").Result = CustName
.FormFields("SAName").Result = SAName
.FormFields("SADeptartment").Result = SADept
.FormFields("SAPhone").Result = SAPhone
Selection.Find.ClearFormatting
With Selection.Find
.Text = ""
.Replacement.Text = ""
.Forward = True
.Wrap = wdFindContinue
.Format = False
.MatchCase = False
.MatchWholeWord = False
.MatchWildcards = False
.MatchSoundsLike = False
.MatchAllWordForms = False
End With
ActiveDocument.Bookmarks("Signature").Range.InlineShapes.AddPicture FileName:= _
SASignaturePath, _
LinkToFile:=False, SaveWithDocument:=True
Selection.Goto What:=wdGoToLine, Which:=wdGoToAbsolute, Count:=1
End With
appword.Visible = True
appword.Activate
Set doc = Nothing
Set appword = Nothing
End Function
Changing and then using the selection as an insertion point is generally bad practice. What you should rather do is use the actual Range of the bookmark, which can be obtained by calling:
ActiveDocument.Bookmarks("BookmarkName").Range
The obtained Range can then be used in your above code instead of Selection, i.e.
ActiveDocument.Bookmarks("BookmarkName").Range.InlineShapes.AddPicture (...)

"Add Record" gives "Can't go to specified record" after first use Access

I have a command button in a form that allows users to add a new record. The command only works the first time you click it after the form is opened. I can navigate through the records without any errors and the first time you add a record after the form is opened will not give errors. Once you try to add a second record, the "Can't go to the specified record" error message is displayed.
I can make edits in the query without a problem and I can edit things without a problem. If I close out of the form and reopen it I can add a new record without issues. Anyone have ideas?
Using VBA, it's the standard add-new code, nothing else. Posted all the code for this form below. Some of the command buttons listed are in macros, don't know if that makes a difference.
Private Sub add_Click()
DoCmd.GoToRecord , , acNewRec
End Sub
Private Sub edit_info_Click()
Date_of_Echo.Locked = False
ID.Locked = False
AoV.Locked = False
AI.Locked = False
MR.Locked = False
TR.Locked = False
TR_velocity.Locked = False
PA_pressures.Locked = False
LVeDD.Locked = False
LVeSD.Locked = False
RV_function.Locked = False
comments.Locked = False
Me.next.Visible = False
Me.previous.Visible = False
Me.first.Visible = False
Me.last.Visible = False
Me.add.Visible = False
Me.save.Visible = True
Me.save.SetFocus
Me.edit_info.Visible = False
End Sub
Private Sub Form_Current()
If Me.NewRecord Then
Me.recordcounter.Caption = "New Record"
Me.next.Visible = False
Me.previous.Visible = False
Me.first.Visible = False
Me.last.Visible = False
Me.add.Visible = False
Me.edit_info.Visible = False
Me.save.Visible = True
Date_of_Echo.Locked = False
ID.Locked = False
AoV.Locked = False
AI.Locked = False
MR.Locked = False
TR.Locked = False
TR_velocity.Locked = False
PA_pressures.Locked = False
LVeDD.Locked = False
LVeSD.Locked = False
RV_function.Locked = False
comments.Locked = False
Else
Me.recordcounter.Caption = "Record " & Me.CurrentRecord & " of " & Me.Recordset.RecordCount
Me.next.Visible = True
Me.previous.Visible = True
Me.first.Visible = True
Me.last.Visible = True
Me.add.Visible = True
Me.edit_info.Visible = True
Me.save.Visible = False
End If
End Sub
Private Sub save_Click()
DoCmd.save
Me.previous.Visible = True
Me.first.Visible = True
Me.last.Visible = True
Me.next.Visible = True
Me.add.Visible = True
Me.edit_info.Visible = True
Me.recordcounter.Caption = "Record " & Me.CurrentRecord & " of " & Me.Recordset.RecordCount
Me.add.SetFocus
Me.save.Visible = False
Date_of_Echo.Locked = True
ID.Locked = True
AoV.Locked = True
AI.Locked = True
MR.Locked = True
TR.Locked = True
TR_velocity.Locked = True
PA_pressures.Locked = True
LVeDD.Locked = True
LVeSD.Locked = True
RV_function.Locked = True
comments.Locked = True
End Sub
Private Sub next_Click()
On Error GoTo Err_cmdLastRecord_Click
Me.AllowAdditions = False
DoCmd.GoToRecord , , acNext
Exit_cmdLastRecord_Click:
Exit Sub
Err_cmdLastRecord_Click:
MsgBox " There are no more records ", vbExclamation, ""
Resume Exit_cmdLastRecord_Click
End Sub
My first thought is that your record isn't saving before you try to go to a new record so try this and see if it fixes the issue.
Private Sub add_Click()
If Me.Dirty Then
Me.Dirty = False
End If
DoCmd.GoToRecord , , acNewRec
End Sub
If anyone is still having this problem, I can't explain why it's happening, but here's a work around:
Reset the AllowAdditionsProperty on the form:
Me.[form_name].Form.AllowAdditions = False
Me.[form_name].Form.AllowAdditions = True
This was a very strange issue because my code had been working fine for weeks. I was using something like this:
Me.frm.SetFocus
DoCmd.GoToRecord , , acNewRec
!Field1 = value1
!Field2 = value2
It was working great, and then out of the blue I started getting the "Can't go to Specified Record" error, even though I had made no changes to the code. The form settings were fine and I could add records all day long in the underlying table. I even checked the form's AllowAdditions property in the Immediate window, and that showed it was set to True. But I tried this work around, and it worked.
Now I add those two lines after every instance of Docmd.GoToNewRoecord, acNewRecord and it's working.
Another thing I have mentioned with the same problem is that you should check the Form data source query. Are all the FIELDS available, are the JOINS correct?
In my case I changed indexed joins from text fields to numeric and it needed update also in Form Data source query.