I am trying to update an inventory stock as follows:
[InventoryStock] = ([CurrentInventoryStock]-[QuantityOrdered])
Note that QuantityOrdered can be decimal, something like: 5.2 or can be full number, something like 8.
The InventoryStock column is set to Number (double)
The QuantityOrdered column is also set to Number (double)
When QuantityOrdered is a full number, like 5, it works perfectly; but when QuantityOrdered is a decimal number, like 7.5 , then I receive:
Run-time error 3144 (syntax error in update statement)
...highlighting the update code that I wrote in VBA.
If Not IsNull(Me.QuantityOrdered) Then
CurrentDb.Execute " UPDATE Inventory SET InventoryStock = InventoryStock - " & Nz(Me.QuantityOrdered.Value, 0) & ""
End If
As described above, my goal is to deducted the quantity ordered (whether decimal or full number) from the Inventory Stock value.
Can someone help me out?
Regarding your problem:
Using implicit string conversion will use a decimal separator following your country/language settings, for example a (,), which causes your issue.
So you should explicitely use Str() to convert the numeric value to a string to get a dot (.) as separator.
Two more small remarks:
NZ(…) is not necessary because you already check that before (If Not IsNull(Me.QuantityOrdered) Then).
Appending just an empty string (& "") is not necessary too.
If Not IsNull(Me.QuantityOrdered) Then
CurrentDb.Execute "UPDATE Inventory SET InventoryStock = InventoryStock - " & Str(Me.QuantityOrdered.Value)
End If
Related
In MS Access I have a table with a Short Text field named txtPMTaskDesc in which some records contains numbers, and if they do, at different positions in the string. I would like to recover these numbers from the text string if possible for sorting purposes.
There are over 26000 records in the table, so I would rather handle it in a query over using VBA loops etc.
Sample Data
While the end goal is to recover the whole number, I was going to start with just identifying the position of the first numerical value in the string. I have tried a few things to no avail like:
InStr(1,[txtPMTaskDesc],"*[0-9]*")
Once I get that, I was going to use it as a part of a Mid() function to pull out it and the character next to it like below. (its a bit dodgy, but there is never more than a two-digit number in the text string)
IIf(InStr(1,[txtPMTaskDesc],"*[0-9]*")>0,Mid([txtPMTaskDesc],InStr(1,[txtPMTaskDesc],"*[0-9]*"),2)*1,0)
Any assistance appreciated.
If data is truly representative and number always preceded by "- No ", then expression in query can be like:
Val(Mid(txtPMTaskDesc, InStr(txtPMTaskDesc, "- No ") + 5))
If there is no match, a 0 will return, however, if field is null, the expression will error.
If string does not have consistent pattern (numbers always in same position or preceded by some distinct character combination that can be used to locate position), don't think can get what you want without VBA. Either loop through string or explore Regular Expressions aka RegEx. Set reference to Microsoft VBScript Regular Expressions x.x library.
Function GetNum(strS AS String)
Dim re As RegExp, Match As Object
Set re = New RegExp
re.Pattern = "[\d+]+"
Set Match = re.Execute(strS)
GetNum = Null
If Match.Count > 0 Then GetNum = Match(0)
End Function
Input of string "Fuel Injector - No 1 - R&I" returns 1.
Place function in a general module and call it from query.
SELECT table.*, GetNum(Nz(txtPMTaskDesc,"")) AS Num FROM table;
Function returns Null if there is no number match.
Well, does the number you want ALWAYS have a - No xxxx - format?
If yes, then you could have this global function in VBA like this:
Public Function GNUM(v As Variant) As Long
If IsNull(v) Then
GNUM = 0
Exit Function
End If
Dim vBuf As Variant
vBuf = Split(v, " - No ")
Dim strRes As String
If UBound(vBuf) > 0 Then
strRes = Split(vBuf(1), "-")(0)
GNUM = Trim(strRes)
Else
GNUM = 0
End If
End Function
Then your sql will be like this:
SELECT BLA, BLA, txtPMTaskDesc, GNUM([txtPMTaskDesc] AS TaskNum
FROM myTable
So you can create/have a public VBA function, and it can be used in the sql query.
It just a question if " - No -" is ALWAYS that format, then THEN the number follows this
So we have "space" "-" "space" "No" "space" "-" -- then the number and the " -"
How well this will work depends on how consistent this text is.
I am using MS-Access to get information from 2 tables. I have used inner join, left, right, and outer with all variations, and it will either pull 1 row when 316 are expected, all data for the fields in test with no values for the fields from test 1, or all data for fields from test 1, and no values for test. How do I resolve this? The actual fields had to be changed for privacy, but the below is the exact layout.
SELECT [TEST].a,
[TEST].b,
[TEST].c,
[TEST 1].[D],
[TEST].E,
[TEST].F,
[TEST].G,
[TEST].H,
[TEST 1].[I],
[TEST].J,
[TEST].K,
[TEST 1].L,
[TEST 1].[M]
FROM [TEST 1]
INNER JOIN [TEST] ON [TEST 1].[ID] = [TEST].[CLAIMSNO];
This is a data-validation and debugging exercise, so if you can't share concrete example data then there is really no definite answer to this question. Technically it may not be answerable according to common StackOverflow standards, but I feel generous right now.
Since the joined fields are text, there are various possibilities keeping them from matching: extra spaces, null-terminated strings, case sensitivity (although Access by default should be case insensitive), wide (Unicode) vs narrow (ASCII, UTF-8) encoding, etc. You did not reveal where the data came from, nor how it was loaded into the database, so I make no assumptions. In order to understand the data and determine the reason for the failed matches, you need to investigate the details of the strings. You could likely narrow the problem by investigating the source of the data values and understanding the range of possible characters, encoding, string termination, etc.
Since you are already having troubles matching data AND since you already indicated that the original tables had no primary key or indexes, I highly recommend adding a new AutoNumber field with a unique index to each table, perhaps named [AID] (for AutoNumber ID). Do this even if you have added indices to existing columns. This will at least provide a reliable "handle" to select and refer to a particular row while debugging the other columns.
The big idea is to use VBA or other built-in functions to inspect and report on various attributes of the string values. There are just too many ways you could do this, but my preference is to create a public VBA function in a normal VBA module and then call this function from an SQL query. Although you could do this for every row, instead I suggest manually choosing rows from each table which you think should match... record the [AID] value for each row. If the manually-selected rows don't result in anything enlightening, then run it against an entire table and see what interesting results you get.
Consider these functions:
Public Function CheckSpaces(val As Variant) As String
Dim result As String
If IsNull(val) Then
result = "Null"
ElseIf VarType(val) = VbVarType.vbString Then
If Len(val) = 0 Then
result = "Empty String"
Else
Dim temp As String
Dim n As Integer, m As Integer
n = Len(val)
result = "Length " & n
temp = LTrim(val)
m = Len(temp)
If n <> m Then
result = result & " AND " & (n - m) & " left spaces"
End If
temp = RTrim(val)
m = Len(temp)
If n <> m Then
result = result & " AND " & (n - m) & " right spaces"
End If
End If
Else
result = "Not a string!"
End If
CheckSpaces = result
End Function
Public Function NullChar(val As Variant) As Boolean
Dim result As Boolean
result = False
If Not IsNull(val) Then
If VarType(val) = VbVarType.vbString Then
If InStr(val, vbNullChar) > 0 Then 'vbNullChar = Chr(0)
result = True
End If
End If
End If
NullChar = result
End Function
And execute queries similar to the following. Let's say that [Test 1] row AID = 10 has [ID] == 'name'. Likewise, imagine row AID == 20 of [Test] has [CLAIMSNO] = ' name ':
SELECT [ID], CheckSpaces([ID]), NullChar([ID])
FROM [TEST 1]
WHERE [AID] = 10
and
SELECT [CLAIMSNO], CheckSpaces([CLAIMSNO]), NullChar([CLAIMSNO])
FROM [TEST]
WHERE [AID] = 20
Compare the returned values. Is there anything that indicates a failed match?
I'm trying to figure out a solution on how to concatenate strings from about 15 different options. Each result comes from a checkbox that is selected based on the state a person has lived in within a certain area.
I know how to turn the checkbox option into a text result. What I'm looking for is how to take these text results, combine them, then ignore null results so there isn't any weird spacing or formatting.
In short, if someone select 3 of the 15 results it would combine the 3 results cleanly and ignore the rest. Example would be: FL, CA, NY
There are, of course, multiple ways that this can be achieved, and since you didn't provide any code or examples of how you are attempting to do this, I will provide two options.
1 - You can concatenate the values using a combination of the & and + operators.
For example, let's say you have 15 checkboxes, all named similarly like chkState01, chkState02 ... through chkState15. And for the simplicity of my sample code, let's assume that when referencing the checkbox control directly in code as chkState01 that it will return either the 2 letter string abbreviation of the State it represents (i.e. NY) if the checkbox was checked, or it will return Null if the checkbox was not checked. With that, you could get your results in 2 ways:
Option A
StateList = (chkState01 + ",") & (chkState02 + ",") & (chkState03 + ",") ....
If those 3 check boxes returned the following values
chkState01 = "NY"
chkState02 = Null
chkState03 = "FL"
Then the result of that concatenation code would be:
NY,FL,
Notice that the string ends with an extra comma (,) and always would since you can't know ahead of time how many of the checkboxes will be checked. You would then need to trim that comma from your list before using it most likely.
Option B
'Create the list with a trailing comma that will need removed
Dim x as Integer
For x = 1 to 15
StateList = StateList & (Me("chkState" & Format(x, "00")) + ",")
Next x
or, you could do:
'Create the list without a trailing comma
Dim x as Integer
For x = 1 to 15
If Not IsNull(Me("chkState" & Format(x, "00"))) Then
If Len(StateList) > 0 Then
StateList = StateList & "," & Me("chkState" & Format(x, "00"))
Else
StateList = Me("chkState" & Format(x, "00"))
End If
End If
Next x
Notice that you can reference a control on a form by "generating" the name of that control as a string and referencing it in the Me("yourcontrolname") format. This is one advantage to naming controls that are similar in a fashion that lends itself to a looping structure like this. The Format command formats the number returned by x as a 2 digit with leading zeros i.e. 1 becomes 01
Further, using & to concatenate two items, where at least one of them is a string, will always result in a string output (Null & "S" = "S"). However, using the + to concatenate two items, where at least one of them is a Null, will always result in Null output (Null + "S" = Null). Hence the checkboxes where the value returns Null does not cause additional commas to be included in the result.
2 - You can write more complicated code to dynamically loop through the checkboxes and build the output list.
More likely, you are going to need to use additional code to determine which checkbox is which state abbreviation and to return the correct string value. Maybe you made the state abbreviation part of the checkbox name i.e. chkState_NY, chkState_FL or maybe you have put the abbreviation in the Tag property of each checkbox.
Let's say you used special control naming chkState_NY, chkState_FL. You could do the following:
Dim ctl as Access.Control
For Each ctl in Me.Controls
If ctl.Name Like "chkState_??" Then
If ctl.Value = True Then
If Len(StateList) > 0 Then
StateList = StateList & "," & Right(ctl.Name,2)
Else
StateList = Right(ctl.Name,2)
End If
End If
End If
Next ctl
I have a query that compares a value. Both values are equal. Data types are double. However, the result is always false. Have you encountered the same scenario?
I tried to round off the data before comparing it and I got the correct results. What do you think is the cause of this issue?
This is a well known side effect of floating numbers.
You have several options. Test for a difference or convert to other data type:
Where Abs(Field1 - Field2) < 0.00001 (or whatever value you consider equal)
Where CCur(Field1) = CCur(Field2)
Where CDec(Field1) = CDecCur(Field2)
Confirm that the values are equal for both variables. Double is floating point with 15 decimal precision, I think. If your display is showing your double variables with rounding, they may appear equal but in fact they may not be equal.
I would recommend you to do Round(variable1, 4) and compare it with Round(variable2, 4). Try testing your variables with a test routine like this:
Public Sub SendDoubles()
Dim a As Double
Dim b As Double
a = 10.0000000001
b = 10.000000001
TestDoubles a, b
End Sub
Public Sub TestDoubles(a As Double, b As Double)
MsgBox CStr(a) & vbCrLf & CStr(b)
MsgBox a = b
MsgBox Round(a, 4) = Round(b, 4)
End Sub
Notice that CStr will convert your double to string so that you can visualize both variable's value. The 2nd MsgBox attempts to compare them as-is and the third one compares them with rounding.
Sorry, another question about MsAccess.
I have data set:
Phone Number
444-514-9864
555-722-2273
333-553- 4535
000-000- 0000
550-322-6888
444-896-5371
322-533-1448
222.449.2931
222.314.5208
222.745.6001
I need it to look like (222) 896-5371.
How do I do it in Ms Access or MsExcel?
You can use the Instr, mid, Left and Right functions to make this work. I have made 1 example, with msdn you should be able to figure out the rest
Dim OldPhoneNumber As String
Dim NewPhoneNumber As String
Dim PreFix As String
Dim PreFix2 As String
' You can replace this line in Access, just make sure the full phone number is stored in "OldPhoneNumber"
OldPhoneNumber = Worksheets(<worksheet name>).Range(<cell name>).Value
PreFix = Left(OldPhoneNumber, InStr(1, OldPhoneNumber, "-", 1))
PreFix2 = Left(OldPhoneNumber, InStr(1, OldPhoneNumber, "-", 1) - 1)
NewPhoneNumber = Replace(OldPhoneNumber, PreFix, "(" & PreFix2 & ") ")
Debug.Print (NewPhoneNumber)
Seeing as not all your phone numbers are formatted the same way, you would have to make a different rule for every different formatted phone number (you need 1 that checks for "-" and one that checks for "." You also might want to filter out the spaces
In Access you set the "Input mask" to : "("000") "000"-"0000;1;_
All the references http://office.microsoft.com/en-ca/access-help/input-mask-syntax-and-examples-HP005187550.aspx
Input mask will only work for new data. You will need to create a macro or function to update your existing data to be consistent with your desired format