我有一个表字段'电话号码',表中的数据是通过数据库中的excel文件链接导入的。该字段的数据类型是文本,因为我们不确定用户如何输入他的电话号码(有时使用国家/地区代码,有时没有国家/地区代码)。
我想在每次更新表格或将数据导入表格后格式化“电话号码”字段。格式[countrycode] - [localcode] - [phone num]。
我不知道该怎么做,是否要创建更新查询或VBA代码来更新此字段。在这方面会有任何帮助。
答案 0 :(得分:0)
通常建议,在数据库字段,该电话号码被保持在数值格式只(意味着没有括号,短划线或诸如此类的东西),因为它提供了数据更稳定和允许更好/更容易未来输出时格式化。最推荐的方法是获取给你的数字并删除所有非数字字符,然后存储该值。
如果您在使用包含此信息的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的模块中(<大骨节病>替代骨节病> + <大骨节病> F11 骨节病>),或在您的接入方式或什么不是,祝你好运。