Home > Blockchain >  Trying to write a VBA function that compares the letters in two words to see if they have any letter
Trying to write a VBA function that compares the letters in two words to see if they have any letter

Time:03-31

The function wordPass is supposed to take two words/strings as parameters and look for letters that they have in common. If they have letters in common, the function returns True, if not, it returns False.

Here is what I tried, but it is not working:

Function wordPass(wordleAnswer As String, guess As String) As Boolean

  For i = 1 To Len(wordleAnswer)
    For j = 1 To Len(guess)
      same = False
      If Mid(guess, j, 1) = Mid(wordleAnswer, i, 1) Then
        same = True
      End If
    Next j
  Next i

  wordPass = same

End Function

CodePudding user response:

We can eliminate one loop using InStr:

Function wordPass(wordleAnswer As String, guess As String) As Boolean
    Dim i As Long
    For i = 1 To Len(guess)
        If InStr(wordleAnswer, Mid$(guess, i, 1)) > 0 Then
            wordPass = True
            Exit Function
        End If
    Next
End Function
  • Related