无法从字符串中提取任何数字

时间:2016-07-19 12:47:47

标签: excel vba

我无法从字符串中删除任何数字。在Excel中,我有许多字符串字段可能包含数字。我只关心数字,其余的字符是不需要的,将被丢弃。号码可以在任何位置,而不是设定的位置。

例如: ' 2捕捉盆地'或者'捕获盆地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

有人能指出我正确的方向吗?非常感谢!!

1 个答案:

答案 0 :(得分:2)

Do While Cells(counter, 1).Value

此处counter为零,但范围索引从1开始,因此出现错误。