2016-07-19 3 views
0

문자열에서 숫자를 제거하는 데 문제가 있습니다. Excel에서 숫자가 포함될 수있는 많은 문자열 필드가 있습니다. 나는 그 숫자에 대해서만 신경을 쓰고 나머지 캐릭터는 원하지 않으므로 버려 질 것이다. 번호는 설정된 위치가 아닌 임의의 위치에있을 수 있습니다.문자열에서 숫자를 추출하는 중 문제가 발생했습니다.

예를 들어

: '2 집수구'또는 'CATCH 유역 × 2'

나는이 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 

누군가 올바른 방향으로 나를 가리킬 수 있습니까? 대단히 감사하겠습니다 !!

답변

2

Do While Cells(counter, 1).Value

여기 counter은 제로이지만 범위 인덱스는 따라서 1 에러 시작한다.

+0

어머나, 나는 그것을 시도했다고 생각했다! 그것은 내 부분에 대한 큰 감독이다. 감사합니다. Alex K, 이제 완벽하게 작동합니다! –

관련 문제