使用多个if语句进行查询

时间:2013-12-20 18:15:13

标签: ms-access access-vba

我想使用以下if语句在sn1列上修改序列号。 如何将以下if语句放入查询?

If Len([sn]) <= 12 Then Me.sn1 = Me.sn 
Else
     If Len([sn]) = 13 And Left([sn], 1) = "S" And Not IsNumeric(Mid([sn], 2, 3)) Then Me.sn1 = Right([sn], 10)

    Else
     If Len([sn]) = 13 And Left([sn], 1) = "S" And IsNumeric(Mid([sn], 2, 3)) Then Me.sn1 = Me.sn

    Else
     If Len([sn]) >= 14 And Not IsNumeric(Right([sn], 1)) Then Me.sn1 = Right([sn], 11)

    Else
      Me.sn1 = Right([sn], 10)

2 个答案:

答案 0 :(得分:0)

if语句以access的SQL风格编写为:

IIF([condition], [true result], [false result])

遵循此语法,您将按如下方式编写语句:

IIf(Len([sn]) <= 12, Me.sn1 = Me.sn, 
IIf(Len([sn]) = 13 And Left([sn], 1) = "S" And Not IsNumeric(Mid([sn], 2, 3)), Me.sn1 = Right([sn], 10),
IIf(Len([sn]) = 13 And Left([sn], 1) = "S" And IsNumeric(Mid([sn], 2, 3)), Me.sn1 = Me.sn,
IIf(Len([sn]) >= 14 And Not IsNumeric(Right([sn], 1)), Me.sn1 = Right([sn], 11),Me.sn1 = Right([sn], 10)))))

在查询中,这将如下所示:

SELECT IIf(Len([sn]) <= 12, Me.sn1 = Me.sn, 
IIf(Len([sn]) = 13 And Left([sn], 1) = "S" And Not IsNumeric(Mid([sn], 2, 3)), Me.sn1 = Right([sn], 10),
IIf(Len([sn]) = 13 And Left([sn], 1) = "S" And IsNumeric(Mid([sn], 2, 3)), Me.sn1 = Me.sn,
IIf(Len([sn]) >= 14 And Not IsNumeric(Right([sn], 1)), Me.sn1 = Right([sn], 11),Me.sn1 = Right([sn], 10))))) AS [SN1]
FROM [SN]

答案 1 :(得分:-1)

您需要向数据库添加一个函数。创建一个新模块并将其粘贴到:

Public Function sn1(sn As String) As String
Dim StringIfs as String

StringIfs = Right(sn, 10)
If Len(sn) <= 12 Then 
   StringIfs = sn 
Else If Len(sn) = 13 And Left(sn, 1) = "S" And Not IsNumeric(Mid(sn, 2, 3)) Then 
   StringIfs = Right(sn, 10)
Else If Len(sn) = 13 And Left(sn, 1) = "S" And IsNumeric(Mid(sn, 2, 3)) Then 
   StringIfs = sn
Else If Len(sn) >= 14 And Not IsNumeric(Right(sn, 1)) Then 
   StringIfs = Right(sn, 11)
End If


  sn1 = StringIfs
End Function

然后,在您的查询中,您会输入以下内容:

MyNewField: sn1(sn)

也就是说,假设您表中的原始字段称为“sn”。如果该字段名为Boo,请将查询字段更改为MyNewField:sn1(Boo)。得到它?您可以将MyNewField更改为您想要的任何内容,但如果该字段应该被称为sn1,那么我建议更改函数名称以避免混淆。