I am trying to have a template form that will load setting from tables. For example i will have a master table with different form IDs and then a textbox table that will have a list of textboxes with what form ID they belong too, their position, their value, and etc. The issue is when i open the form in design mode the code doesn't run and if I try and set the view to design mode i get and error saying "you cant switch to a different view at this time" with a code of 2174. here is the code i am using right now, all the values are hard coded so i know i don't have any errors with the reading from the database or anything. Any help is greatly appreciated!
Option Compare Database
Private Sub Form_Load()
loadSettings
End Sub
Private Sub loadSettings()
Dim ctl As Access.Control
On Error GoTo ERR_Line
DoCmd.RunCommand acCmdDesignView
Set ctl = CreateControl(Me.Name, acTextBox, acDetail, , , 100, 100, 100, 100)
ctl.Name = "txt1"
ctl.Value = "test"
DoCmd.RunCommand (acCmdFormView)
ERR_Line:
MsgBox Err.Description & " Error Number " & Err
End Sub
If i use a module with this code in it, it will go into design mode but gives a "Microsoft Access cant add, rename, or delet the control(s) you requested." error number 29054.
Option Compare Database
Sub loadSettings(frmName As String)
Dim frm As Form
Dim ctl As Access.Control
On Error GoTo ERR_Line
Set frm = Application.Forms(frmName)
DoCmd.Close acForm, frmName
DoCmd.OpenForm frmName, acDesign
Set ctl = CreateControl(frmName, acTextBox, acDetail, , , 100, 100, 100, 100)
ctl.Name = "txt1"
ctl.Value = "test"
DoCmd.Close acForm, frmName, acSaveYes
DoCmd.OpenForm frmName, acNormal, , , , , "asdf"
ERR_Line:
MsgBox Err.Description & " Error Number " & Err
End Sub
Related
I have a macro to delete values from a table I would like to add the last time this macro run.
I manage to find a way to input Date inside of it and save, but when I open Access again, it has the original value in it.
My code is as follows:
Private Sub Comando0_Click()
dataate = InputBox("Periodo a ser deletado até [DD/MM/AAAA]:")
If IsDate(dataate) Then
dataate = Format(CDate(dataate), "dd\/mm\/yyyy")
End If
Dim qdf As DAO.QueryDef
Dim count As Long
Set qdf = CurrentDb().QueryDefs("Teste 1")
With qdf
.Parameters("[prmDataAte]").Value = CDate(dataate)
.Execute dbFailOnError
count = .RecordsAffected
End With
MsgBox " " & count & " registros foram apagados da tbl_tabela_de_preco"
Me.teste3.Caption = Now
DoCmd.Save acForm, Me.Name
End Sub
So far I tried using textbox and labels and had encountered the same problem.
And tried other codes that i found:
theFormName = Me.OpenArgs
Set theform = Forms.Item("Formulário1")
Me.teste3.Caption = Now
theform.teste2.Caption = "Dados excluídos até: " & dataate
DoCmd.Save acForm, Me.Name
DoCmd.Save , "Formulário1"
DoCmd.Close acForm, Me.Name, acSaveNo
Issues with your code:
If IsDate(dataate) Then
dataate = Format(CDate(dataate), "dd\/mm\/yyyy")
End If
This has no Else or Exit Sub clause, so the rest of the code will run always, even if no valid date was entered.
Me.teste3.Caption = Now
DoCmd.Save acForm, Me.Name
You can set control properties (like Caption) in Form View, but you cannot save them permanently. So the DoCmd.Save has no effect here.
You would have to do this in Design View. But this is not a good way to do this.
Better: in Form_Load(), read the date from the table where you saved it with the update query. Then set the caption with that date.
I am trying to write a code that will print out my current form for the current record. This is what I am using:
Private Sub PrintCommand_Click()
Dim myform As Form
Dim pageno As Long
pageno = Me.CurrentRecord
Set myform = Screen.ActiveForm
DoCmd.SelectObject acForm, myform.Name, True
DoCmd.PrintOut acPages, pageno, pageno, , 1
DoCmd.SelectObject acForm, myform.Name, False
End Sub
When I dimension "pageno" as an integer, it gives me an overflow error for some of my records that exceed 65000. So, I dimensioned it as a long data type, but then I receive the following error:
Run-time error '2498': An expression you entered is the wrong data type for one of the arguments."
I also tried making "pageno" a variant data type, and I received the same 2498 error message. Any suggestions on either a way to fix this or another work around for printing my form for the current record?
Update: This works and accomplishes what I was going for...
Private Sub PrintCommand_Click()
'Print out the current record
Me.Filter = "[Quote Number] = " & QuoteNumberEntry.Value
Me.FilterOn = True
DoCmd.PrintOut
Me.Filter = ""
Me.FilterOn = False
End Sub
I have a textbox that dynamically filters a listbox on the same form as you type. The listbox filters perfectly, but the selected value is not saving correctly. For example, if you click on the fourth value after filtering the listbox and then close the form, it actually saves what would have been the fourth value had the list not been filtered.
Here is the code:
Private Sub txtSearch_Change()
'CODE THAT HANDLES WHAT HAPPENS WHEN THE USER TYPES IN THE SEARCH BOX
Dim strFullList As String
Dim strFilteredList As String
If blnSpace = False Then
Me.Refresh 'refresh to make sure the text box changes are actually available to use
'specify the default/full rowsource for the control
strFullList = "SELECT [Project ID], [Project Name] FROM [Admin: Projects] ORDER BY [Project Name];"
'specify the way you want the rowsource to be filtered based on the user's entry
strFilteredList = "SELECT [Project ID], [Project Name] FROM [Admin: Projects] WHERE [Project Name] LIKE ""*" & Me.txtSearch.Value & "*"" ORDER BY [Project Name]"
'run the search
fLiveSearch Me.txtSearch, Me.lstItems, strFullList, strFilteredList, Me.txtCount
End If
End Sub
Private Sub txtSearch_KeyPress(KeyAscii As Integer)
'NECESSARY TO IDENTIFY IF THE USER IS HITTING THE SPACEBAR
'IN WHICH CASE WE WANT TO IGNORE THE INPUT
On Error GoTo err_handle
If KeyAscii = 32 Then
blnSpace = True
Else
blnSpace = False
End If
Exit Sub
err_handle:
Select Case Err.Number
Case Else
MsgBox "An unexpected error has occurred: " & vbCrLf & Err.Description & _
vbCrLf & "Error " & Err.Number & "(" & Erl & ")"
End Select
End Sub
Private Sub txtSearch_GotFocus()
' USED TO REMOVE THE PROMPT IF THE CONTROL GETS FOCUS
On Error Resume Next
If Me.txtSearch.Value = "(type to search)" Then
Me.txtSearch.Value = ""
End If
End Sub
Private Sub txtSearch_LostFocus()
' USED TO ADD THE PROMPT BACK IN IF THE CONTROL LOSES FOCUS
On Error Resume Next
If Me.txtSearch.Value = "" Then
Me.txtSearch.Value = "(type to search)"
End If
End Sub
Private Sub Form_Close()
DoCmd.SetWarnings False
End Sub
I've inherited this database and am trying to fix up areas that are not working. I'm definitely a novice and I can't seem to figure out where the error might be in the code that is causing the wrong value to save to the record. Any guidance would be appreciated.
Replace:
'run the search
fLiveSearch Me.txtSearch, Me.lstItems, strFullList, strFilteredList, Me.txtCount
With
me.lstitems.rowsourcetype = "Table/Query"
me.lstitems.rowsource = strfilteredlist
I am sending data from frmSearchEmployeeWorksheets to frmStatsCorr which runs a query (qryStatsCorr). On frmStatsCorr I am checking to make sure the query returns records otherwise I will Msg the user and return to the search form. My problem is that I am having problems 'ignoring' the 2501 caused by the DoCmd.OpenForm ("frmStatsCorr") which I learned here on Stackoverflow...
What am I doing wrong that is causing me major Access VBA Frustration??
This is the sub on the Search form (frmSearchEmployeeWorksheets):
Private Sub btnSearch_Click()
' I only change focus to force the updated data to submit to query
Me.[txtEmployee].SetFocus
Me.txtShift.SetFocus
If txtUnit = "7" Then
'First close the form in order to update
DoCmd.Close acForm, "frmStatsCorr"
' Open Stats form
On Error GoTo myErr
**DoCmd.OpenForm ("frmStatsCorr") 'causes error**
End If
myExit:
Exit Sub
myErr:
Echo True
If Err.Number = 2501 Then GoTo myExit
MsgBox Err.Description
GoTo myExit
End Sub
In frmStatsCorr I simply check to make sure the query returns records if not I inform the user, close the form, and return to the frmSearchEmployeeWorksheets
Private Sub Form_Load()
If strFormStatus = "view" Then
If DCount("*", "qryStatsCorr") = 0 Then
MsgBox "Your search does not produce any results. Try a different search.", vbOKOnly
DoCmd.Close
DoCmd.OpenForm ("frmSearchEmployeeWorksheets")
Exit Sub
End If
txtDay = WeekdayName(Weekday(Me.WorkDate)) 'This line returns an error so I check for an empty query and return to the search form.
Me.[WorkDate].SetFocus
Me.txtUnit.Enabled = False...
I'm unsure how well I understand your code or the logic behind it. My hunch is you should check the DCount result from btnSearch_Click, and not fiddle with closing then re-opening frmStatsCorr, and having frmStatsCorr close itself when it contains no data. Just do not open frmStatsCorr when it will not contain data.
If the current form (frmSearchEmployeeWorksheets) which holds your btnSearch_Click procedure contains unsaved data changes, you can save them with Me.Dirty = False
Private Sub btnSearch_Click()
Dim strPrompt As String
If Me.Dirty Then ' unsaved data changes
Me.Dirty = False ' save them
End If
If Me.txtUnit = "7" Then
If DCount("*", "qryStatsCorr") = 0 Then
strPrompt = "Your search does not produce any results. " & _
"Try a different search."
MsgBox strPrompt, vbOKOnly
Else
' if frmStatsCorr is open, just Requery
' else open frmStatsCorr
If CurrentProject.AllForms("frmStatsCorr").IsLoaded Then
Forms("frmStatsCorr").Requery
Else
DoCmd.OpenForm "frmStatsCorr"
End If
' uncomment next line to close current form
'DoCmd.Close acForm, Me.Name
End If
End If
End Sub
If frmStatsCorr is open and you need to check whether it is in Design View, examine its CurrentView property.
Forms("frmStatsCorr").CurrentView ' Design View = 0
I suggested that approach because I suspected frmStatsCorr's Form_Load may trigger the 2501 error when it closes itself. But I'm not certain that's the cause of the error and I'm not motivated enough to set up a test.
If you still have 2501 errors with the approach I suggested, there are two other possible causes I've encountered:
corruption
broken references
I try to improve a report I made to document databases, by adding a VBA line count to Modules and Forms. The following code works perfectly in a standard module:
Sub test()
Dim accObj As AccessObject, bwasOpen As Boolean, objName As String
objName = "Form1"
Set accObj = CurrentProject.AllForms(objName)
bwasOpen = accObj.IsLoaded
If Not bwasOpen Then
DoCmd.OpenForm objName, acDesign, WindowMode:=acHidden
End If
If Forms(objName).HasModule Then
DoCmd.OpenModule "Form_" & objName
Debug.Print Modules("Form_" & objName).CountOfLines
End If
If Not bwasOpen Then
DoCmd.Close acForm, objName, acSaveNo
End If
End Sub
But when I use a similar code in the report itself, I have an error. And since that error is happening in the class module (the report), I feel a bit stuck with debugging. The code in the report:
Set accObj = CurrentProject.AllForms(objName)
bwasOpen = accObj.IsLoaded
If Not bwasOpen Then
DoCmd.OpenForm objName, acDesign, WindowMode:=acHidden 'Breaks here
End If
If Forms(objName).HasModule Then
DoCmd.OpenModule "Form_" & objName
GetExtraInfo = Modules("Form_" & objName).CountOfLines
End If
If Not bwasOpen Then
DoCmd.Close acForm, objName, acSaveNo
End If
The code is called from a report control using =GetExtraInfo(). The whole thing works well, except this new part where I want to return the CountOfLines for Forms.
Update: I have added some error trapping, and it gives error:
2486 - You can't carry out this action at the present time
The whole db can be downloaded here, its's only 300 KB. The report is named "rptObjList".
The "bad" code has been commented out. It is an Access 2003 db.
Thanks for your help.
Your code opens a form and checks its .HasModule property. And if the form has a module, you open that module to check .CountOfLines. However, you need not open the module to determine its .CountOfLines. And I would try to avoid opening the form, too.
? VBE.ActiveVBProject.VBComponents("Form_Form1").CodeModule.CountOfLines
6
If you ask for .CountOfLines for a module which doesn't exist, such as the following, you can trap error #9 ('Subscript out of range') to give you an alternative to checking the .HasModule property:
? VBE.ActiveVBProject.VBComponents("bogus").CodeModule.CountOfLines
Or you could check for the code module with a function similar to minimally tested ModuleExists() outlined below.
Note I'm unsure how helpful my suggestions will be because I struggled to follow your code. Furthermore I unwisely chose to step through the code behind rptObjList and became frustrated by all the unhandled errors when it calls GetDesc() for objects which have no Description property. I just gave up.
Public Function ModuleExists(ByVal pModule As String, _
Optional ByVal pProject As String = "") As Boolean
Dim blnReturn As Boolean
Dim objVBProject As Object
Dim strMsg As String
On Error GoTo ErrorHandler
If Len(pProject) = 0 Then
Set objVBProject = VBE.ActiveVBProject
Else
Set objVBProject = VBE.VBProjects(pProject)
End If
blnReturn = Len(objVBProject.VBComponents(pModule).Name) > 0
ExitHere:
Set objVBProject = Nothing
ModuleExists = blnReturn
Exit Function
ErrorHandler:
Select Case Err.Number
Case 9 ' Subscript out of range
' no such module; function returns False
Case Else
strMsg = "Error " & Err.Number & " (" & Err.Description _
& ") in procedure ModuleExists"
MsgBox strMsg
End Select
GoTo ExitHere
End Function