Chcę znaleźć, czy ciąg znaków zawiera ","(przecinek) w nim. Czy mamy jakąś inną opcję niż czytanie char-by-char?
Użyj funkcji Instr.
Dim pos As Integer
pos = InStr("find the comma, in the string", ",")
zwróci 15 w poz.
Jeśli nie zostanie znaleziony, zwróci 0.
Jeśli potrzebujesz znaleźć przecinek za pomocą formuły Excela, możesz użyć funkcji =FIND(",";A1)
.
Zauważ, że jeśli chcesz użyć Instr
do znalezienia pozycji łańcucha bez rozróżniania wielkości liter, użyj trzeciego parametru Instr i nadaj mu const vbTextCompare
(lub tylko 1 dla die-hards).
Dim posOf_A As Integer
posOf_A = InStr(1, "find the comma, in the string", "A", vbTextCompare)
da ci wartość 14.
Zauważ, że musisz określić pozycję początkową w tym przypadku, jak podano w specyfikacji, którą połączyłem: Argument start jest wymagany, jeśli określono compare.
Istnieje również funkcja InStrRev, która robi to samo, ale rozpoczyna wyszukiwanie od końca tekstu do jego początku.
Per @rene's odpowiedź ...
Dim pos As Integer
pos = InStrRev("find the comma, in the string", ",")
...nadal zwracałby 15 do pos, ale jeśli ciąg ma więcej niż jeden z wyszukiwanego ciągu, jak słowo "the", to:
Dim pos As Integer
pos = InStrRev("find the comma, in the string", "the")
...zwróciłoby 20 do pos, zamiast 6.
Opierając się na odpowiedzi Rene'a, mógłbyś również napisać funkcję, która zwracałaby albo TRUE, jeśli podłańcuch był obecny, albo FALSE, jeśli nie był'a:
Public Function Contains(strBaseString As String, strSearchTerm As String) As Boolean
'Purpose: Returns TRUE if one string exists within another
On Error GoTo ErrorMessage
Contains = InStr(strBaseString, strSearchTerm)
Exit Function
ErrorMessage:
MsgBox "The database has generated an error. Please contact the database administrator, quoting the following error message: '" & Err.Description & "'", vbCritical, "Database Error"
End
End Function