Reputation: 3235
I am using Visual Basic 6
I am trying to find the position of a value in a string
The find code seems to be working the issue is the code adds the information to a list box twice
Position 2 Value 2
Position 2 Value 2
Position 4 Value 2
Position 4 Value 2
The string to search will always be 1 to 9 values in some random order each time
The code as written now is only searching for one value
My question is how to only add the Position and Value ONCE to the listbox?
Private Sub Form_Load()
Dim S1, S2, MyPos As String
Dim I As Integer
I = 1
S1 = "123245"
S2 = "2"
tbOne.Text = S1
Do Until I = 5 'This will be Len(S1) - 1 later
MyPos = InStr(I, S1, S2, 1)
tbTwo.Text = tbTwo.Text & MyPos & vbNewLine
'If MyPos = S2 Then
lbOne.AddItem "Position " & MyPos & " " & "Value " & S2
'End If
I = I + 1
Loop
End Sub
Upvotes: 0
Views: 370
Reputation: 8868
This seems to do what you need:
Option Explicit
Private Sub Form_Load()
Dim S1 As String, S2 As String, MyPos As String
Dim i As Integer
S1 = "123245"
S2 = "2"
tbOne.Text = S1
For i = 1 To Len(S1) - 1
If Mid(S1, i, 1) = S2 Then
tbTwo.Text = tbTwo.Text & i & vbNewLine
lbOne.AddItem "Position " & i & " " & "Value " & S2
End If
Next
End Sub
Note that you have to specify the type when declaring variables on the same line, unless you intended for them to be of type Variant.
Upvotes: 2