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

MS Access: how to delete everything in a string after two specific characters

当我的数据如下所示时,如何删除字符串中的数字和 space:

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

我设法使用更新查询(如下所示)删除了“=”之后的所有内容,但如何同时更新两者(使用“=”和“:”)?

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

我可以在两个单独的查询中完成它,而它只是带有“=”或“:”的数据,但是当我还有 "type of contact 594837" 这样的数据时,我不知道如何处理它。也许有一种方法可以删除所有数字、= 和 : 符号?

相当简单.. 您可以编写一个 VBA 函数,您可以将其实际嵌入到 SQL 查询中来执行此操作。我转到数据库工具(MS Access 顶部)、Visual Basic,右键单击模块文件夹,插入 -> 模块。 write/copy 代码后,转到 Visual Basic for Applications IDE 顶部的调试,然后单击“编译 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

错误处理不多,但我认为这回答了您的问题。

我扔在了一个Table,字段数据类型是Text:

Table


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 是函数名。

如果有任何我遗漏的地方 - 请告诉我,我会尽力改正。