【问题标题】:MS Access: how to delete everything in a string after two specific charactersMS Access:如何在两个特定字符后删除字符串中的所有内容
【发布时间】:2015-03-15 06:43:10
【问题描述】:

当我的数据看起来像这样时,如何删除数字和字符串中的空格:

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 "*=*"

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

【问题讨论】:

标签: string ms-access


【解决方案1】:

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

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

我把它扔到了一个表格里,字段数据类型是文本:

表格


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

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

【讨论】:

  • 我离开了我的电脑哈哈你能编辑一下吗? @HansUp
  • @HansUp 你做了什么吗?我所看到的只是将trm 更改为Variant.. 顺便谢谢
  • 当 fieldToTest 为 Null 时,将 trm 声明为 Variant 而不是 String 可避免 trm = fieldToTest 出现“无效使用 Null”错误。
  • @HansUp 明白了。不知道那个。谢谢.. 周末愉快
  • @Invent-Animate 感谢您的帮助!我刚刚意识到我的表中还有不同类型的数据,即“家庭地址更改 59604934”和数字数量的变化,关于如何删除这些有什么想法吗?我只想在里面有文字
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-07-16
  • 2021-11-26
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多