Hi folks,
I'm trying to use the following code to check for the existence of more than one string (ie (1) or (2) or (3) or (4)) in a filename in order to remove these strings from the filename
I'm getting a "Data Type Mismatch" error when the routine goes into the function on the line "For i = 0 To UBound(ArrayVals)"
I suspect it's because I'm looking for a string and not a number.
Can anyone point me in the right direction please
Sub CeckArray() Dim ArrayVals ArrayVals = Array((1), (2), (3), (4)) ' start loop here to check wksheet If InArray("(3)") Then Debug.Print "Value is in Array" End If End Sub Function InArray(strValue) Dim i For i = 0 To UBound(ArrayVals) If ArrayVals(i) = CStr(strValue) Then InArray = True Exit Function End If Next InArray = False End Function
Many thanks
Seamus
Last edited by SOS; 08-18-2011 at 09:00 AM. Reason: Marking thread as Solved
Use regular expressions
use like soFunction StringContains(ByVal LookAt As String, ByVal LookFor As String) As Boolean Dim RegEx As Object Set RegEx = CreateObject("VBScript.RegExp") RegEx.Pattern = "[" & LookFor & "]" RegEx.Global = True StringContains = RegEx.Test(LookAt) Set RegEx = Nothing End Function
?StringContains("Bob12is4her23e", 1234)
The problem is probably that your function does not have access to the array variable that you've defined.
My lightly re-written version of your code seems to work fine...
Sub Test() Dim asTestArray() asTestArray = Array("(1)", "(2)", "(3)") MsgBox InArray("(3)", asTestArray()) End Sub Function InArray(ByVal sSearchVal As String, asSearchArray()) As Boolean Dim lArrayLoop As Long Dim bTempVal As Boolean bTempVal = False For lArrayLoop = LBound(asSearchArray) To UBound(asSearchArray) If asSearchArray(lArrayLoop) = sSearchVal Then bTempVal = True End If Next lArrayLoop InArray = bTempVal End Function
hi, SOS, for the matter of learning:
Sub CeckArray() Dim ArrayVals ArrayVals = Array("1", "2", "3", "4") ' start loop here to check wksheet If InArray(ArrayVals, "3") Then Debug.Print "Value is in Array" End If End Sub Function InArray(x, strValue) Dim i For i = 0 To UBound(x) If x(i) = strValue Then InArray = True Exit Function End If Next InArray = False End Function
You can't use instr for an array, use 'match' instead.
You can use instr for a stringSub snb() sn = Array("(1)", "(2)", "(3)", "(4)") msgbox Application.Match("(3)", sn, 0) End Sub
Sub snb2() sn = Array("(1)", "(2)", "(3)", "(4)") msgbox instr(Join(sn),"(3)") End Sub
Last edited by snb; 08-18-2011 at 09:01 AM.
Wow, what can I say? I knew this was the place to come for an answer. Such speedy (and correct) replies.
Many thanks
Seamus
There are currently 1 users browsing this thread. (0 members and 1 guests)
Bookmarks