我在MS Access DB的一个表中工作。我想使用iif语句来确定字段A中的值是否符合有效格式(在这种情况下,一个或两个数字后跟一个字母)。如果是这样,我想只取字段A的数字部分(例如,如果字段A的条目是“15B”,我想只考虑“15”部分)并将其插入当前空字段我创造的B。
如何编写仅考虑字段A的数字部分然后将其插入字段B的MS Access查询?
答案 0 :(得分:1)
您还需要id字段
Private Sub bntStart_Click()
On Error GoTo err_trap
Dim con As ADODB.Connection
Dim rsLocal, rsLocal_Upd As ADODB.Recordset
Dim sql_string As String
Dim counter, numeric_value As Integer
Set counter = 1
sql_string = "SELECT * FROM TblTest"
Set con = CurrentProject.Connection
Set rsLocal = con.Execute(sql_string)
If Not (rsLocal.BOF And rsLocal.EOF) Then
rsLocal.MoveFirst
While Not rsLocal.EOF
If Len(ExtractNumber(rsLocal.Fields("FieldA")) > 0) Then
numeric_value = ExtractNumber(rsLocal.Fields("FieldA"))
sql_string = "UPDATE TblTerms SET FieldB = " & numeric_value & " WHERE id = " & counter
Set con = CurrentProject.Connection
Set rsLocal_Upd = con.Execute(sql_string)
End If
rsLocal.MoveNext
counter = counter + 1
Wend
End If
Set con = Nothing
Exit Sub
err_trap:
MsgBox (Err.Description)
Set con = Nothing
End Sub
Function ExtractNumber(str As Srting)
Dim iCount As Integer, i As Integer
Dim sText As String
Dim lNum As String
'Written by OzGrid Business Applications
'[url]www.ozgrid.com[/url]
'Extracts a number from a cell containing text And numbers.
sText = str
For iCount = Len(sText) To 1 Step -1
If IsNumeric(Mid(sText, iCount, 1)) Then
i = i + 1
lNum = Mid(sText, iCount, 1) & lNum
End If
If i = 1 Then lNum = CInt(Mid(lNum, 1, 1))
Next iCount
ExtractNumber = CLng(lNum)
End Function
请注意,我从这里获取了ExtractNumber http://www.ozgrid.com/forum/showthread.php?t=18185
答案 1 :(得分:1)
对于您描述的模式,您可以使用like
构建更新查询,如下所示:
UPDATE tbl1 SET tbl1.ValB =
Switch([ValA] Like "#[a-z]",Left([valA],1),
[valA] Like "##[a-z]",Left([valA],2),True,NULL);
或者使用Val
函数,它会尝试尽可能多地从字符串转换为数字:
UPDATE tbl1 SET tbl1.ValB =
iif(valA like "#[a-z]" or valA like "##[a-z]",val(ValA),NULL)
答案 2 :(得分:1)
对于问题的验证部分,您可以使用Like
模式匹配。以下是立即窗口中的示例。
? "15A" Like "#[A-Z]" Or "15A" Like "##[A-Z]"
True
? "4B" Like "#[A-Z]" Or "4B" Like "##[A-Z]"
True
? "123A" Like "##[A-Z]" Or "123A" Like "##[A-Z]"
False
? "15AB" Like "#[A-Z]" Or "15AB" Like "##[A-Z]"
False
? "15!" Like "#[A-Z]" Or "15!" Like "##[A-Z]"
False
如果这些测试正确表达了您的意图,您可以将其用作Field A
的验证规则:
Like "#[A-Z]" Or Like "##[A-Z]"
对于Field B
,您可以在查询中创建一个字段表达式。
SELECT
[Field A],
Val([Field A]) AS [Field B]
FROM YourTable;
在您需要的任何地方使用该查询[Field B]
。使用这种方法,如果您的表格中不存在[Field B]
,那么只要[Field B]
值发生变化,您就不必担心更新[Field A]
存储的值。