Ik wil weten of een string een “,”(komma) bevat. Hebben we een andere optie dan char-by-char lezen?
Antwoord 1, autoriteit 100%
Gebruik de Instr-functie
Dim pos As Integer
pos = InStr("find the comma, in the string", ",")
geeft 15 in pos terug
Als het niet wordt gevonden, wordt er 0 geretourneerd
Als u de komma met een Excel-formule moet vinden, kunt u de functie =FIND(",";A1)
gebruiken.
Merk op dat als u Instr
wilt gebruiken om de positie van een tekenreeks hoofdletterongevoelig te vinden, de derde parameter van Instr moet gebruiken en deze de const vbTextCompare
(of gewoon 1 voor die-hards).
Dim posOf_A As Integer
posOf_A = InStr(1, "find the comma, in the string", "A", vbTextCompare)
geeft u een waarde van 14.
Merk op dat u in dit geval de startpositie moet specificeren zoals vermeld in de specificatie die ik heb gekoppeld: Het startargument is vereist als vergelijken is opgegeven.
Antwoord 2, autoriteit 19%
Je kunt ook het speciale woord like
gebruiken:
Public Sub Search()
If "My Big String with, in the middle" Like "*,*" Then
Debug.Print ("Found ','")
End If
End Sub
Antwoord 3, autoriteit 6%
Er is ook de functie InStrRev die de hetzelfde soort dingen, maar begint te zoeken vanaf het einde van de tekst tot het begin.
Per antwoord van @rene…
Dim pos As Integer
pos = InStrRev("find the comma, in the string", ",")
…zou nog steeds 15 teruggeven aan pos, maar als de tekenreeks meer dan één van de zoekreeksen heeft, zoals het woord “de”, dan:
Dim pos As Integer
pos = InStrRev("find the comma, in the string", "the")
…zou 20 teruggeven aan pos, in plaats van 6.
Antwoord 4, autoriteit 4%
Voortbouwend op het antwoord van Rene, zou je ook een functie kunnen schrijven die TRUE teruggeeft als de substring aanwezig was, of FALSE als dat niet het geval was:
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
Antwoord 5
Je zou dit niet echt willen doen gezien de bestaande Instr/InstrRev-functies, maar er zijn momenten dat het handig is om EVALUATE te gebruiken om het resultaat van Excel-werkbladfuncties binnen VBA te retourneren
Option Explicit
Public Sub test()
Debug.Print ContainsSubString("bc", "abc,d")
End Sub
Public Function ContainsSubString(ByVal substring As String, ByVal testString As String) As Boolean
'substring = string to test for; testString = string to search
ContainsSubString = Evaluate("=ISNUMBER(FIND(" & Chr$(34) & substring & Chr$(34) & ", " & Chr$(34) & testString & Chr$(34) & "))")
End Function