【问题标题】:Trouble pulling out any number from string无法从字符串中提取任何数字
【发布时间】: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

有人能指出我正确的方向吗?将不胜感激!

【问题讨论】:

    标签: excel vba


    【解决方案1】:

    Do While Cells(counter, 1).Value

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

    【讨论】:

    • 天哪,我以为我试过了!这是我的一个很大的疏忽。感谢 Alex K,它现在完美运行!
    猜你喜欢
    • 1970-01-01
    • 2014-07-15
    • 2021-02-28
    • 2021-11-27
    • 2019-06-03
    相关资源
    最近更新 更多