1

我有一个表格字段“电话号码”,表格中的数据是通过数据库中的 excel 文件链接导入的。该字段的数据类型是文本,因为我们不确定用户如何输入他的电话号码(有时带有国家代码,有时没有国家代码)。

每次更新表格或将数据导入表格后,我想格式化“电话号码”字段。格式[国家代码]-[本地代码]-[电话号码]。

我不知道该怎么做,是否创建更新查询或 VBA 代码来更新此字段。将在这方面提供任何帮助。

4

1 回答 1

1

通常建议在数据库字段中,电话号码仅以数字格式维护(意味着没有括号、破折号或诸如此类的东西),因为它为数据提供了更高的稳定性,并允许在输出时更好/更容易地格式化。最推荐的方法是获取给您的数字并将其去除所有非数字字符,然后存储该值。

如果您在将其放入数据库之前使用包含此信息的 Excel 表,那么您可以简单地格式化包含电话号码的列以将所有内容转换为单个数值,例如 800-555-1212 或 (888) 222 -1515 将变为 8005551212 和 8882221515。这可以使用 Excel 中内置的现有单元格格式选项来完成,或者如果您想要动态完成,则在字段具有值时触发的简单 VBA 代码也可以解决问题。

编辑#1(超级简单的功能)

Public Function numOnly(sToClean As String) As String
    Const NUM_CHARS = "0123456789"
    Dim lChar As Long
    Dim sResult As String
    For lChar = 1 To Len(sToClean)
        If InStr(1, NUM_CHARS, Mid$(sToClean, lChar, 1)) > 0 Then
            'Found a numeric character
            sResult = sResult + Mid$(sToClean, lChar, 1)
        End If
    Next
    'Return the result
    numOnly = sResult
End Function

编辑#2(更多功能高级版)

Option Explicit 

Public Function stripChars(CheckStr As String, Optional KillNums As Boolean = False, Optional AllowedChars As String, Optional NotAllowed As String) 

     ' CheckStr = the string being evaluated
     ' KillNums [True/False] = remove numbers/remove non-numeric
     ' AllowedChars = what to allow even if you are removing non-numeric (aka KillNums=False) [ex. "$,."] or removing numbers (aka KillNums=True) [ex. "6,9"]
     ' NotAllowed = override characters never allowed and processed before any other option (meaning if you have it in both allow/not allow - not allow takes precedence
     ' NOTE: AllowedChars and NotAllowed arguments are *not* case-sensitive

    Dim Counter As Long 
    Dim TestChar As String 
    Dim TestAsc As Long 

     ' Loop through characters
    For Counter = 1 To Len(CheckStr) 
         ' Get current character and its ANSI number
        TestChar = Mid(CheckStr, Counter, 1) 
        TestAsc = Asc(TestChar) 

         ' Test first to see if current character is never allowed
        If InStr(1, NotAllowed, TestChar, vbTextCompare) > 0 Then 
             ' do nothing

             ' If current character is in AllowedChars, keep it
        ElseIf InStr(1, AllowedChars, TestChar, vbTextCompare) > 0 Then 
            stripChars = stripChars & TestChar 

             ' If KillNums=True, test for not being in numeric range for ANSI
        ElseIf KillNums Then 'only allow non-numbers
            If TestAsc < 48 Or TestAsc > 57 Then 
                stripChars = stripChars & TestChar 
            End If 

             ' If KillNums=False, test for being in numeric ANSI range
        Else 'only allow numbers
            If TestAsc >= 48 And TestAsc <= 57 Then 
                stripChars = stripChars & TestChar 
            End If 
        End If 
    Next 

End Function 

您可以在 Excel 的模块 ( Alt+ F11) 或 Access 表单中删除其中任何一个,祝你好运。

于 2013-09-14T16:59:04.063 回答