我有一个MS Access数据库表,其中包含德国客户的记录。我在MS Excel中有一个用户表单,我在其中输入要搜索的名称。提交表单后,它会在VBA中创建搜索查询,建立与数据库的连接并运行查询:
SELECT CustomerNumber FROM CustomerTable WHERE (CustomerName LIKE '%loffel%');
问题是,该客户在数据库中记录为“Löffel”。当我搜索'loffel'时,它不会返回任何结果。
有没有办法搜索Unicode字符并仍能找到结果?
答案 0 :(得分:1)
以下是您可能会考虑的解决方法。它不是很漂亮,但似乎确实有用。
这个想法是让用户输入一个没有重音字符的搜索词,VBA代码将用可能的变体列表替换指定的非重音字母,例如: o
替换为[oö]
,所以
... LIKE '%loffel%'
变为
... LIKE '%l[oö]ffel%'
使用这样的代码:
Option Explicit
Sub so38010103()
Dim oChars As String
' e.g., U+00F6 is "Latin Small Letter O With Diaeresis"
oChars = "[o" & ChrW(&HF6) & "]"
' (add other accented "o"s above, and other character lists below, as needed)
'test data
Const searchFor = "loffel"
Dim conn As New ADODB.Connection
conn.Open _
"DRIVER={Microsoft Access Driver (*.mdb, *.accdb)};" & _
"DBQ=C:\Users\Public\so38010103.accdb"
Dim cmd As New ADODB.Command
cmd.ActiveConnection = conn
cmd.CommandType = adCmdText
cmd.CommandText = "SELECT COUNT(*) AS n FROM CustomerTable WHERE (CustomerName LIKE ?)"
cmd.Parameters.Append cmd.CreateParameter("?", adVarWChar, adParamInput, 255)
Dim rst As ADODB.Recordset
' test 1: literal search
cmd.Parameters(0).Value = "%" & searchFor & "%"
Set rst = cmd.Execute
Debug.Print rst(0).Value & " record(s) found" ' 0 record(s) found
rst.Close
' test 2: replace "o" with list of accented variants
cmd.Parameters(0).Value = "%" & Replace(searchFor, "o", oChars, 1, -1, vbTextCompare) & "%"
Set rst = cmd.Execute
Debug.Print rst(0).Value & " record(s) found" ' 1 record(s) found
rst.Close
conn.Close
End Sub