MS Access:如何在两个特定字符后删除字符串中的所有内容

时间:2015-01-16 15:49:47

标签: string ms-access

如何将数字与字符串中的空格一起删除,而我的数据如下所示:

randomtext = 567897
otherrandomtext = 3827475
evendifferentone : 483838
andsoon : 03948
type of contact 594837
other type of contact 453222223

这样看起来像这样:

randomtext
otherrandomtext
evendifferentone
andsoon
type of contact
other type of contact

我设法使用更新查询(如下所示)删除" ="之后的所有内容。但是如何同时更新两者(使用" ="和":#34;)?

UPDATE [MyTable] 
SET [Name] = Left([Name], InStr([Name], "=") - 1)
WHERE [Name] Like "*=*"

我可以在两个单独的查询中执行此操作,而只有" ="或者":",但是当我还有像#34;联系人类型594837"这样的数据时,我不知道如何处理它。也许有一种方法可以删除所有数字,=和:符号?

1 个答案:

答案 0 :(得分:1)

相当简单..您可以编写一个VBA函数,您可以实际嵌入到SQL查询中来执行此操作。我去了数据库工具(MS Access的顶部),Visual Basic,右键单击模块文件夹,插入 - >模块。编写/复制代码后,转到Visual Basic for Applications IDE顶部的Debug,然后单击“编译 YourDatabaseName

见下文:

Option Compare Database
Option Explicit

Public Function TrimString(fieldToTest As Variant) As Variant

Dim test, test2 As Variant
Dim trm As Variant
Dim intSearch, lngth As Integer

TrimString = Null

test = InStr(fieldToTest, "=")
test2 = InStr(fieldToTest, ":")
lngth = Len(fieldToTest)


If test > 0 Then
    'We know it contains an equals sign

    trm = Left(fieldToTest, test - 1)
    trm = Trim(trm)
    Debug.Print trm

ElseIf test2 > 0 Then
    'We know it contains a colon
    trm = Left(fieldToTest, test2 - 1)
    trm = Trim(trm)
    Debug.Print trm

ElseIf lngth > 0 Then
    'Find out if it has integers in it
    'Rebuild the string without Integers
    For intSearch = 1 To lngth
         If Not IsNumeric(Mid$(fieldToTest, intSearch, 1)) Then
          trm = trm & Mid$(fieldToTest, intSearch, 1)
        Else
        End If
    Next

    trm = Trim(trm)
Else
    'Regular String
    'Do Nothing
    trm = fieldToTest
End If

TrimString = trm

End Function

没有太多的错误处理,但我认为这可以回答你的问题。

我把它扔在一个表中,字段数据类型是Text:


ID  stringTest (Field Name)

 1. randomtext = 123453
 2. otherrandmtext = 543555
 3. evendifferentone : 453553
 4. andsoon : 05453534

输出:


 ID Expr1

 1. randomtext
 2. otherrandmtext
 3. evendifferentone
 4. andsoon

SQL:


SELECT Table2.ID, 
TrimString([stringTest]) AS Expr1
FROM Table2;

回想一下VBA代码TrimString是函数名。

如果有什么我忽略了 - 请告诉我,我会尽力纠正它。

相关问题