Excel macro “type mismatch” error while looping through a column
-
03-07-2021 - |
Question
Every call of this Function results in a Runtime Error '13' Type Mismatch. Why does this happen?
Public Function VersionExists(versionId As String)
VersionExists = False
For Each cell In Tabelle2.Columns(1)
If cell.Value = versionId Then
VersionExists = True
End If
Next
End Function
Solution
Here is an alternative as I suggested in the comment
Public Function VersionExists(versionId As String) As Boolean
Dim aCell As Range, rng As Range
Set rng = Tabelle2.Columns(1)
Set aCell = rng.Find(What:=versionId, LookIn:=xlValues, _
LookAt:=xlWhole, SearchOrder:=xlByRows, SearchDirection:=xlNext, _
MatchCase:=False, SearchFormat:=False)
If Not aCell Is Nothing Then VersionExists = True
End Function
OTHER TIPS
You can't access cell.value
from .Columns(1)
as it returns a range encompassing the entire column, instead;
For Each cell In Sheet1.Columns(1).Rows '//or .cells
Probably a good idea to exit the for loop after a match too.
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow