Voglio scoprire se una stringa contiene un “,” (virgola) in esso. Abbiamo altre opzioni oltre a leggere char-by-char?
Usa la funzione Instr
Dim pos As Integer pos = InStr("find the comma, in the string", ",")
restituirà 15 in pos
Se non trovato, restituirà 0
Se hai bisogno di trovare la virgola con una formula excel puoi usare la funzione =FIND(",";A1)
.
Si noti che se si desidera utilizzare Instr
per trovare la posizione di una stringa non sensibile alla distinzione tra maiuscole e minuscole, utilizzare il terzo parametro di Instr e assegnargli il const vbTextCompare
(o solo 1 per die-hard).
Dim posOf_A As Integer posOf_A = InStr(1, "find the comma, in the string", "A", vbTextCompare)
ti darà un valore di 14.
Nota che devi specificare la posizione iniziale in questo caso come indicato nella specifica I linked: L’argomento start è richiesto se compare il confronto.
Puoi anche usare la parola speciale like
:
Public Sub Search() If "My Big String with, in the middle" Like "*,*" Then Debug.Print ("Found ','") End If End Sub
C’è anche la funzione InStrRev che fa lo stesso tipo di cosa, ma inizia la ricerca dalla fine del testo all’inizio.
Per @ rene’s answer …
Dim pos As Integer pos = InStrRev("find the comma, in the string", ",")
… restituirebbe comunque 15 in pos, ma se la stringa ha più di una stringa di ricerca, come la parola “the”, allora:
Dim pos As Integer pos = InStrRev("find the comma, in the string", "the")
… restituirebbe 20 a pos, invece di 6.
Basandosi sulla risposta di Rene, potresti anche scrivere una funzione che restituisce TRUE se la sottostringa era presente, o FALSE se non lo era:
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