Simple Function Errors when Running in Access - ms-access

I am very new to program and VBA. I am trying to play around with VBA in Access so I wrote this little thing to test my understanding. However, when I git run, it pops up empty Macro dialog/window instead of a Message box says the things in the code ( I thought it would). Could anyone take 5 secs to let me know what did I miss please. Thank you very much
Public Function AddOne(value As Integer) As Integer
AddOne = value + 1
End Function
MsgBox "Adding 1 to 5 gives:" & AddOne(5)

It's not possible to Run a macro that takes any arguments/parameters from the "Run" dialog.
So if you press Run button, or F5, you'll see the Dialog box because that is Excel asking you "Which procedure do you want to run".
It will display any available procedures. Procedures which take any argument(s) will not be visible, since the arguments would not be supplied.
A few other points:
Your MsgBox statement is outside of the function. It should be inside the function
Function AddOne(val As Integer)
Dim ret As Integer
ret = val + 1
'Display msgBox:
MsgBox "Adding 1 to " & val & " gives:" & ret
'return to caller:
AddOne = ret
End Function
Since you can't run from the dialog, you need to invoke this manually from the Immediate window:
Or, you can simply print the result to immediate window using the following in the Immediate pane:
?AddOne(5)
Which will print "6" in the Immmediate.

Related

Access remove line break in string, program tells it's NULL

I have code that does something then you press enter in textfield, problem is when you use Ctrl+Enter, i can capture that event but access tells me in next line that that field is apparently NULL
Private Sub Text5_KeyPress(KeyAscii As Integer)
If KeyAscii = vbKeyReturn Or KeyAscii = 10 Then
If Len(Me.Text5) = 0 Then Exit Sub
If Val(Right(Me.Text5, 1)) > 2 Then Me.Text5 = Left(Me.Text5, Len(Me.Text5) - 1) & "0"
So 'Len' works fine, but the 'Right' function gives out 'Invalid use of null', when i hit debug and check the value it is NULL
I can't figure it out
I guess i need to remove new line characters but how to do that when the text box is null and every function for strings spits out that error
The problem with your check is that Len(Null) is not 0, it's Null.
There are a couple ways to get around this. First, as mentioned in the comments, you can simply add a check for IsNull:
If IsNull(Me.Text5) Or Len(Me.Text5) = 0 Then
The other way you can do this is force it to coalesce by concatenating vbNullString:
If Len(Me.Text5 & vbNullString) = 0 Then
Also you could use Nz and set a return value of your wish in case if the expression is null, in this example also vbNullString and check the result of this function:
If Nz(Me.Text5, vbNullString) = vbNullString Then
or
If Len(Nz(Me.Text5, vbNullString) = 0) Then
or
If Nz(Me.Text5, 0) = 0 Then
or
If Not Nz(Me.Text5, False) Then
For sure you can store the result in a variable first and then check and work with this later on.
Whatever fulfills your needs.
Well, i test it as much as i can and it's just that when you use Ctrl+Enter on a field and capture the key press, field will be null for some reason, i don't see possible way around this

VBA - Error 3167 Record deleted

I know there's similar posts as this one, but i have not managed to resolve my error by reading them, so i'm posting.
I m trying to make an input form in Ms Access, the user will input two barcodes, and then he ll press a button to commit those values to a table, the process will be repeated until he needs to store said table, in which case there's another button event for that. When they enter each set of records to the input boxes and hit commit, the record is saved, and all the fields are cleared, cursor is going to barcode1 field to await new entries.
The problem starts when, after one successful execution of everything, if i rerun the database, and restart everything, when i try to press the button to commit a new entry into the table, i get the following error:
Error 3167: Record is Deleted
If i close (x) the application and restart it, everything works normally again.
Here's the relevant code, with the point the debugger gives me the error:
Private Sub CommitButton_Click()
'If (Me!Barcode1 = "**************************") Or IsNull(Me!Barcode1) Or IsNull(Me!Barcode2) Then
'If (Len(Me!Barcode1) < 2) Or (Len(Me!Barcode2) < 2) Then
len_barcode1 = Len(Me!Barcode1)
len_barcode2 = Len(Me!Barcode2)
If (len_barcode1 < 1 Or IsNull(len_barcode1)) Or (len_barcode2 < 1 Or IsNull(len_barcode2)) Then
MsgBox ("IS NULL - NOT SAVING")
Else
MsgBox ("IS NOT NULL - SAVING")
fld2 = Barcode2.Value
fixed = Mid(fld2, 6, 14)
Barcode2.Value = fixed
'DoCmd.SetWarnings (WarningsOff)
DoCmd.RunCommand acCmdSaveRecord
DoCmd.GoToRecord acDataForm, "BarCodeDataForm", acNext, 1
Me.Barcode1.SetFocus
'DoCmd.SetWarnings (WarningsOn)
Me.Barcode1.Value = Null
Me.Barcode2.Value = Null
Me.ValuePrice.Value = Null
Me.Barcode1.SetFocus
End If
End Sub
As you see, there is a manual change to a value (Barcode2), the error appears on exactly the next line:
DoCmd.RunCommand acCmdSaveRecord
Is there a way to commit the changes or resolve this? Thank you

Global Date Variable Works Only for Entered Values

I'm currently working on what should be a relatively simple database, which is very close to being at its end, until I hit the inevitable problem.
I'm using Global Variables and a Form to collect parameters to pass into the Criteria portion of a Query, which works just fine for the first two, which are basic strings and integers.
Then comes the dates, which work, so long as you chose a date from the DatePicker that is entered into the query.
For example, if the query field holds 6/1/2014, 6/3/2014, and 6/8/2014, and the date 6/5/2014 is picked, the form will crash and go blank, though if you pick 6/8/2014, it'll go on as it should.
I had tried a variety of different forms of the code, but in the most basic form I simple have:
Between Get_Global('GBL_Start_Date_ID') AND Get_Global('GBL_End_Date_ID')
I'm not sure if I should be limiting the DatePicker based on the values entered in the query, or if there's a more robust way of going about this, or maybe I just completely missed a simple checkbox.
EDIT
My code for the Global Variables looks like this:
Option Compare Database
Global GBL_Start_Date_ID As Date
Global GBL_End_Date_ID As Date
Global GBL_Customer_ID As Long
Global GBL_Engineer_ID As Long
Public Function Init_Globals()
GBL_Start_Date_ID = #6/1/2014#
GBL_End_Date_ID = #6/30/2014#
GBL_Customer_ID = 1
GBL_Engineer_ID = 1
End Function
Public Function Get_Global(gbl_parm)
Select Case gbl_parm
Case "GBL_Customer_ID"
Get_Global = GBL_Customer_ID
Case "GBL_Engineer_ID"
Get_Global = GBL_Engineer_ID
Case "GBL_Start_Date_ID"
Get_Global = GBL_Start_Date_ID
Case "GBL_End_Date_ID"
Get_Global = GBL_End_Date_ID
End Select
End Function
And I just add a simple line to the AfterUpdate event of the ComboBoxes and TextBoxes to assign the variable:
GBL_Engineer_ID = Me.EngineerSelection
Thanks in advance,
Aaron
You can do two things. Fix the query as it is written or make it much more robust.
To fix it as written
Between "#" & Get_Global('GBL_Start_Date_ID') & "#" AND "#" & Get_Global('GBL_End_Date_ID') & "#"
OR
change your Get_Global function
Public Function Get_Global(gbl_parm)
Select Case gbl_parm
Case "GBL_Customer_ID"
Get_Global = GBL_Customer_ID
Case "GBL_Engineer_ID"
Get_Global = GBL_Engineer_ID
Case "GBL_Start_Date_ID"
Get_Global = "#" & GBL_Start_Date_ID & "#"
Case "GBL_End_Date_ID"
Get_Global = "#" & GBL_End_Date_ID & "#"
End Select
End Function
You are correctly specifying that the values of GBL_Start_Date_ID and GBL_End_Date_ID are dates by using #s when you create them however when you use them in your query they appear without them. You can prove to yourself this is what is happening by typing ?#1/1/2014# into the immediate window. The date is printed as 1/1/2014 which when used in your query, makes Between 6/1/2014 AND 6/30/2014 which is a syntax error.
To make things all that much better you need to parameterize this part of your query. Change this
Between Get_Global('GBL_Start_Date_ID') AND Get_Global('GBL_End_Date_ID')
to this
Between pStartDate AND pEndDate
Before you call your query you need to do your usual checks: are either of these null? is pStartDate < pEndDate?
By performing these checks and parameterizing this you ensure that you never end up with a query like this. Calling your query means you need to need to populate the parameters with DAO or ADO.
Between AND

How do I set a function to a variable in MATLAB

As a homework assignment, I'm writing a code that uses the bisection method to calculate the root of a function with one variable within a range. I created a user function that does the calculations, but one of the inputs of the function is supposed to be "fun" which is supposed to be set equal to the function.
Here is my code, before I go on:
function [ Ts ] = BisectionRoot( fun,a,b,TolMax )
%This function finds the value of Ts by finding the root of a given function within a given range to a given
%tolerance, using the Bisection Method.
Fa = fun(a);
Fb = fun(b);
if Fa * Fb > 0
disp('Error: The function has no roots in between the given bounds')
else
xNS = (a + b)/2;
toli = abs((b-a)/2);
FxNS = fun(xns);
if FxNS == 0
Ts = xNS;
break
end
if toli , TolMax
Ts = xNS;
break
end
if fun(a) * FxNS < 0
b = xNS;
else
a = xNS;
end
end
Ts
end
The input arguments are defined by our teacher, so I can't mess with them. We're supposed to set those variables in the command window before running the function. That way, we can use the program later on for other things. (Even though I think fzero() can be used to do this)
My problem is that I'm not sure how to set fun to something, and then use that in a way that I can do fun(a) or fun(b). In our book they do something they call defining f(x) as an anonymous function. They do this for an example problem:
F = # (x) 8-4.5*(x-sin(x))
But when I try doing that, I get the error, Error: Unexpected MATLAB operator.
If you guys want to try running the program to test your solutions before posting (hopefully my program works!) you can use these variables from an example in the book:
fun = 8 - 4.5*(x - sin(x))
a = 2
b = 3
TolMax = .001
The answer the get in the book for using those is 2.430664.
I'm sure the answer to this is incredibly easy and straightforward, but for some reason, I can't find a way to do it! Thank you for your help.
To get you going, it looks like your example is missing some syntax. Instead of either of these (from your question):
fun = 8 - 4.5*(x - sin(x)) % Missing function handle declaration symbol "#"
F = # (x) 8-4.5*(x-sin9(x)) %Unless you have defined it, there is no function "sin9"
Use
fun = #(x) 8 - 4.5*(x - sin(x))
Then you would call your function like this:
fun = #(x) 8 - 4.5*(x - sin(x));
a = 2;
b = 3;
TolMax = .001;
root = BisectionRoot( fun,a,b,TolMax );
To debug (which you will need to do), use the debugger.
The command dbstop if error stops execution and opens the file at the point of the problem, letting you examine the variable values and function stack.
Clicking on the "-" marks in the editor creates a break point, forcing the function to pause execution at that point, again so that you can examine the contents. Note that you can step through the code line by line using the debug buttons at the top of the editor.
dbquit quits debug mode
dbclear all clears all break points

Allow user to separate dates with period in MS Access

I am working with an Access database where I have a form that contains several date entry fields. I have a new user that is used to using a period as a delimiter for dates so instead of "6/22/11" or "6-22-11", they enter "6.22.11". I would like to continue to allow this type of entry, but Access converts "6.22.11" to a time instead of a date. I have tried setting the format on the text box to "Short Date" with no help. I have also tried adding code to the "Lost Focus" event but that is to late since Access has already done the conversion. The "Before Update" event fires before the conversion but will not allow me to change the text in the textbox. Any ideas on how I can allow all three forms of date entry?
your above example
Private Sub Texto0_KeyPress(KeyAscii As Integer)
If Chr(KeyAscii) = "." Then
KeyAscii = Asc("/")
End If
End Sub
works for me.
Another aproximation is play with the BeforeUpdate and AfterUpdate events.
In BeforeUpdate you cannot modify de content of the control, but you can set a flag (a variable defined at module/form level) in the AfterUpdate event and change the content: it will trigger again the BeforeUpdate, but in this case, because is flagged you sould ignore it and unflag.
http://office.microsoft.com/en-us/access-help/control-data-entry-formats-with-input-masks-HA010096452.aspx
Input Mask.
I wrote the following function for a user who was used to entering 6 and 8 digit dates in input masks by just typing a string of numbers with no delimiter. You should be able to modify it for your purposes:
'---------------------------------------------------------------------------
' Purpose : Enables entry of 8-digit dates with no delimiters: 12312008
' Usage : Set OnChange: =DateCtlChange([Form].[ActiveControl])
' 8/ 6/09 : Allow entry of 6-digit dates with no delimiters
' (year 2019 and 2020 must still be entered as 8-digit dates)
'---------------------------------------------------------------------------
Function DateCtlChange(DateCtl As TextBox)
Dim s As String, NewS As String
On Error GoTo Err_DateCtlChange
s = DateCtl.Text
Select Case Len(s)
Case 6
If s Like "######" Then
If Right(s, 2) <> "19" And Right(s, 2) <> "20" Then
NewS = Left(s, 2) & "/" & Mid(s, 3, 2) & "/" & Mid(s, 5, 2)
End If
End If
Case 8
If s Like "########" Then
NewS = Left(s, 2) & "/" & Mid(s, 3, 2) & "/" & Mid(s, 5, 4)
End If
End Select
If IsDate(NewS) Then
DateCtl.Text = NewS
DateCtl.SelStart = Len(DateCtl.Text)
End If
Exit_DateCtlChange:
Exit Function
Err_DateCtlChange:
Select Case Err.Number
'Error 2101 is raised when we try to set the text to a date
' that fails the date control's validation
Case 2101 'The setting you entered isn't valid for this property.
'Log error but don't show user
Case Else
'Add your custom error logging here
End Select
Resume Exit_DateCtlChange
End Function
Access uses the system date and time format to determine how to translate a value. Another option - that would affect every program on this user's computer - is this: http://office.microsoft.com/en-us/access-help/change-the-default-date-time-number-or-measurement-format-HA010351415.aspx?CTT=1#BM2
Alternatively you can use spaces instead of slashes in dates in Access. Thus the user can use the left hand on the space bar and use the right hand on the numeric keyboard. I feel this is much easier to use than either the slash or the hyphen.