【发布时间】:2016-07-19 20:51:36
【问题描述】:
我无法从字符串中删除任何数字。在 Excel 中,我有许多可能包含数字的字符串字段。我只关心数字,其余字符是不需要的,将被丢弃。数字可以在任何位置,而不是固定位置。
例如: '2 CATCH BASINS' 或 'CATCH BASINS x2'
我的代码基于这个SO 答案,但我似乎无法让它工作。错误消息是“应用程序定义的或对象定义的错误”。
Option Explicit
Function onlyDigits(s As String) As String
' Variables needed (remember to use "option explicit"). '
Dim retval As String ' This is the return string. '
Dim i As Integer ' Counter for character position. '
' Initialise return string to empty '
retval = ""
' For every character in input string, copy digits to '
' return string. '
For i = 1 To Len(s)
If Mid(s, i, 1) >= "0" And Mid(s, i, 1) <= "9" Then
retval = retval + Mid(s, i, 1)
End If
Next
' Then return the return string. '
onlyDigits = retval
End Function
Public Sub CommandButton1_Click()
Application.ScreenUpdating = False
' -----------------------------------------------------------------------------------------
' Will strip numbers from descriptions for basins, guy wires, water meters/valves & pull box
' -----------------------------------------------------------------------------------------
Dim counter As Integer 'Index for the While Loop
Dim fCode As String 'Variable for column E, feature code
Dim fDesc As String 'Variable for column F, the descriptor
Do While Cells(counter, 1).Value <> "" 'While the first column has any data, keep looping
fCode = Cells(counter, 5).Value 'Populate feature code variable from column E
If (fCode = "XCB") Or (fCode = "XGW") Or (fCode = "XWV") Or (fCode = "XWM") Then
fDesc = Cells(counter, 6).Value
Cells(counter, 6).Value = onlyDigits(fDesc)
Else
'do nothing
End If
counter = counter + 1
Loop 'Finishes checking for numbers within specific descriptors
有人能指出我正确的方向吗?将不胜感激!
【问题讨论】: