用于检查文本字段的功能

时间:2013-10-13 19:55:29

标签: vba ms-access ms-access-2007 access-vba

我正在使用Access 2007,我需要一个能检查文本字段的函数,如果找到某个单词,它将根据查找表返回一个值

例如我有一个文本字段如下:

    ID                   Text
|    1     |  engineers for mechanical work  
|    2     |  engineers for civil work       
|    3     |  engineers for electrical work 

我的查询表如下:

     Checkwords             showords
 |   mechanical      |   mechanical engineer
 |   civil           |   civil engineer
 |   chemical        |   chemical engineer
 |   electrical      |   electrical engineer
 |   maintenance     |   maintenance engineer
 |   electronics     |   electronics engineer

我需要检查文本记录的功能,如果找到“ mechanical ”这样的文本,它将显示“机械工程师”,如果找到“ civil 等文本“它将展示”土木工程师“等等。

我要检查大约200个字,所以我需要一个使用带有“like”参数的查找表的函数......这是可能的???

2 个答案:

答案 0 :(得分:0)

(1)用于提取关键字的自定义VBA函数:

Function ExtractKeyword(ByVal Text)
  Text = Mid(Text, InStr(Text, " for ") + 5)
  If Right(Text, 5) = " work" Then
    ExtractKeyword = Left(Text, Len(Text) - 5)
  Else
    ExtractKeyword = Text
  End If
End Function

(2)使用它的查询:

SELECT MainTable.ID, LookupTable.ShowWords
FROM MainTable LEFT JOIN
     LookupTable ON ExtractKeyword(MainTable.Text) = LookupTable.CheckWords
ORDER BY MainTable.ID

答案 1 :(得分:0)

那么,一个更通用的版本,虽然会被警告 - 你越依赖VBA而不是SQL,大量甚至不那么大的数据就会越慢:

(1)添加一个类模块,将其命名为LookupData,并将以下字段添加到其中:

Public Key As String
Public Value As String

(2)在标准模块中,定义以下功能:

Function LookupShowWords(ByVal Text)
  If IsNull(Text) Then
    LookupShowWords = Null
    Exit Function
  End If
  Dim Data As LookupData
  Static LookupTable As VBA.Collection
  If LookupTable Is Nothing Then
    Set LookupTable = New VBA.Collection
    Dim RS As DAO.Recordset
    Set RS = CurrentDb.OpenRecordset("LookupTable", dbOpenForwardOnly)
    While Not RS.EOF
      Set Data = New LookupData
      Data.Key = "*" + RS(0) + "*"
      Data.Value = RS(1)
      LookupTable.Add Data
      RS.MoveNext
    Wend
  End If
  Dim S As String
  For Each Data In LookupTable
    If Text Like Data.Key Then
      If Len(S) = 0 Then
        S = Data.Value
      Else
        S = S + ";" + Data.Value
      End If
    End If
  Next
  If Len(S) = 0 Then LookupShowWords = Null Else LookupShowWords = S
End Function

(3)现在可以重写列出结果的查询,使其看起来像这样:

SELECT ID, LookupShowWords(Text) AS ShowWords FROM MainTable ORDER BY ID;

请注意,(2)中的假设是查找表本质上是静态的,在这种情况下,它的内容可以在调用之间安全地缓存。