避免#Func!访问查询错误

Avoiding #Func! Error in Access Query

我在 Access 中有一个格式如下的字段:Los Angeles, CA #00001

我需要将文本字段修改为如下所示:#001 - 加利福尼亚州洛杉矶

为此,我使用了这个公式:

 "#" & Format([STORE NUMBER],"000") & " - " & Trim(Left([STORE NAME],InStr(1,[STORE NAME],"#")-1))

我 运行 遇到的问题是,并非我的数据集中的每条记录都采用相同的格式。在某些情况下,位置名称是: "Test Store for California"。

如果是这种情况,我会得到一个“#Func!”错误,可能是因为没有要查找以应用公式的“#”符号。

任何人都可以协助找到避免此错误的解决方法。

理想情况下,如果输出确实导致“#Func!”,我会喜欢它。错误,只是像这样使用原始名称:

+------------------------+------------------------+
|        Original        |          New           |
+------------------------+------------------------+
| Los Angeles, CA #00001 | #001 - Los Angeles, CA |
| Test Store for CA      | Test Store for CA      |
| San Diego, CA #00002   | #002 - San Diego, CA   |
+------------------------+------------------------+

您可以使用函数 return 格式化值,如果 # 不存在,则 return 原始值。

Public Function SplitStore(ByVal value_ As String) As String

    If InStr(1, value_, "#") = 0 Then
        SplitStore = value_
        Exit Function
    End If

    Dim arr As Variant
        arr = Split(value_, "#")

    SplitStore = "#" & Format(arr(1), "000") & " -" & arr(0)
End Function

调用它:

SELECT SplitStore([STORE NUMBER]) As FormattedStore
...


'#001 -Los Angeles, CA 

您可以在使用 InStr:

搜索 "#" 之前将 "#" 附加到字符串的末尾
"#" & Format([STORE NUMBER],"000") & " - " & Trim(Left([STORE NAME],InStr(1,[STORE NAME]&"#","#")-1))

如果 "#" 已经存在,InStr 将找到现有的位置。如果不存在,那么 InStr(1,[STORE NAME]&"#","#")-1 将只是 return [STORE NAME] 的长度,因此 Left 将只是 return 整个字段。