for loop question

lezawang

Well-known Member
Joined
Mar 27, 2016
Messages
1,805
Office Version
  1. 2016
Platform
  1. Windows
Hi
I made a spelling mistake in the code below but still working fine.
the currentpostion in the loop
Rich (BB code):
 For x = currentpostion To Len(phrase)
is wrong spelling. I stepped in the code and it is always 0. However, the code worked fine.
Why is that? Thank you



Rich (BB code):
Sub onlynumber()
    Dim phrase As String
    Dim lenght As Integer
    Dim currentpostion As Integer
    Dim temp As String
    currentposition = 1
    Dim x As Integer
    
    phrase = InputBox("enter string")
    For x = currentpostion To Len(phrase)
        If (IsNumeric(Mid(phrase, currentposition, 1))) = True Then
        temp = temp & Mid(phrase, currentposition, 1)
        End If
        currentposition = currentposition + 1
    Next x
    MsgBox (temp)
End Sub
 

Excel Facts

When did Power Query debut in Excel?
Although it was an add-in in Excel 2010 & Excel 2013, Power Query became a part of Excel in 2016, in Data, Get & Transform Data.
You actually do not need that variable at all in your code. It is redundant and unnecessary.
However, I would add an IF statement to make sure that the length of "phrase" is greater than 0 before going in to your loop, i.e.
Code:
Sub onlynumber()

    Dim phrase As String
    Dim temp As String
    Dim x As Integer
    
    phrase = InputBox("enter string")
    If Len(phrase) > 0 Then
        For x = 1 To Len(phrase)
            If (IsNumeric(Mid(phrase, x, 1))) = True Then
                 temp = temp & Mid(phrase, x, 1)
            End If
        Next x
        MsgBox (temp)
    End If
    
End Sub
 
Last edited:
Upvote 0

Forum statistics

Threads
1,223,894
Messages
6,175,252
Members
452,623
Latest member
Techenthusiast

We've detected that you are using an adblocker.

We have a great community of people providing Excel help here, but the hosting costs are enormous. You can help keep this site running by allowing ads on MrExcel.com.
Allow Ads at MrExcel

Which adblocker are you using?

Disable AdBlock

Follow these easy steps to disable AdBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the icon in the browser’s toolbar.
2)Click on the "Pause on this site" option.
Go back

Disable AdBlock Plus

Follow these easy steps to disable AdBlock Plus

1)Click on the icon in the browser’s toolbar.
2)Click on the toggle to disable it for "mrexcel.com".
Go back

Disable uBlock Origin

Follow these easy steps to disable uBlock Origin

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back

Disable uBlock

Follow these easy steps to disable uBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back
Back
Top