VBA type Mismatch error,how can I be sure I'm defining the right value type to variables? - excel

I'm trying to compare an String value and add a String result from that String Value, it throws an error type 13, I believe the error relies in the "Range" property,it works If I don't define an range and leave a single Cell value, but I need to check the same logic for a certain range.
Sub Vars()
'myVar = 20'
'MsgBox myVar'
Dim currencyVar As Double
Dim locationRange As String
Dim RangeResult As String
locationRange = Application.Sheets("Sheet4").Range("F3:F19")
RangeResult = Sheets("Sheet4").Range("G3:G19")
Debug.Print (locationRange)
mainXlookup = WorksheetFunction.XLookup(Sheets("Sheet4").Range("b3:b19"), Sheets("Sheet3").Range("b2:b18"), Sheets("Sheet3").Range("c2:c18"), "Not in project")
Sheets("Sheet4").Range("f3:f19") = mainXlookup
If locationRange = "Bethesda" Then
RangeResult = "In-Range"
End If
End Sub

Related

msoShapeOval entered in cell not allowed to be value for variable declared as MsoShapeType

In the attached code everything works except assigning the value to shpOval3.
I am trying to take the text from a cell and assign it to a variable declared as MsoShapeType.
1) The code misfires with Type mismatch when it attempts to assign the cell value of msoShapeOval to shpOval3 (declared as MsoShapeType).
2) If I try strOval4 (string) instead in .Shapes.AddShape(strOval4, Left, Top, Width, Height) it also misfires and says Type mismatch.
I am trying to avoid converting to an msoShapeType constant in the cell as the cell value is loaded into a combobox on a form and the value of 9 is meaningless to the users. I can convert if necessary but am looking for a solution without converting.
Sub ShpType()
Dim shpOval1 As Long
Dim shpOval2 As MsoShapeType
Dim shpOval3 As MsoShapeType
Dim strOval4 As String
Sheets("Data").Range("Company1Shape") = "msoShapeOval"
shpOval1 = msoShapeOval
shpOval2 = msoShapeOval
shpOval3 = Sheets("Data").Range("Company1Shape")
strOval4 = Sheets("Data").Range("Company1Shape")
Debug.Print "shpOval1 = "; shpOval1
Debug.Print "shpOval2 = "; shpOval2
Debug.Print Sheets("Data").Range("Company1Shape")
Debug.Print "shpOval3 = "; shpOval3
Debug.Print "strOval4 = "; strOval4
End Sub
Debugger results with shpOval3 commented out
shpOval1 = 9
shpOval2 = 9
msoShapeOval
shpOval3 = 0
strOval4 = msoShapeOval
You can use a Select Case statement to test your string and assign the appropriate constant to a variable declared as msoAutoShapeType...
Dim strShapeType As String
strShapeType = Sheets("Data").Range("Company1Shape")
Dim shapeType As MsoAutoShapeType
Select Case strShapeType
Case "msoShapeOval"
shapeType = msoShapeOval
Case "msoShapeRectangle"
shapeType = msoShapeRectangle
'etc
'
'
'
End Select
Hope this helps!

How to access the value of a string when defining within a loop

I would like to access the value of a string when declaring new variables so that I can declare new variables within a loop.
I have tried val(), creating a function. An simplified version of my problem can be found in the code below.
Function StudentValue(x As String) As String
StudentValue = x
End Function
Public Sub TEST()
Dim i As Integer
Dim strName As String
Dim n As Integer
n = 20
For i = 1 To n
strName = "Variable" & CStr(i)
'The problem occurs with the next two lines,
'once active they create a string with the name 'strName' and not the
'value of the string eg 'Variable1', 'Variable2', ect
'Attempt1
'Dim strName As String
'Attempt2
'Dim NameFunction(strName) As String
Next i
End Sub
The errors are as follows:
Dim strName As String results in "compile error: Duplicate declaration in current scope"
Dim NameFunction(strName) As String results in "compile error: Constant expression required"
Is there a function that allows you to access the value of a string when declaring variables?
Thank you in advance!
You are getting "Duplicate declaration" Error because you are trying to declare a variable by the same name.
You are getting the error "Constant expression required" Error because Dim XYZ() as string is the syntax for declaring an array. And the value inside the brackets specifies the size of the array and must be constant.
Here is a link on how to use arrays.
Use Option Explicit, it will help you solve problems before they are problems.
Here is your code using arrays.
Option Explicit
Function StudentValue(x As String) As String
StudentValue = CStr(x)
End Function
Public Sub TEST()
Const MaxNumNames As Integer = 20
Dim i As Integer
Dim strNames(1 To MaxNumNames) As String
For i = 1 To MaxNumNames
'This will populate the array of names
strNames(i) = "Variable" & CStr(i)
'To use the name in the loop
Debug.Print "In Loop:" & strNames(i)
Next i
'To use the name outside the loop (Show 5th name)
Debug.Print "Outside Loop: " & strNames(5)
' To use the name in your function outside the loop (Using 2nd Name)
Debug.Print "Using Function: " & StudentValue(strNames(2))
End Sub

VBA Subscript out of range, name resolution problem?

Trying to write a VBA function that will return the column number given the header cell string and the worksheet name but I get the Subscript out of range error.
Here is the function:
Public Function namedColumnNo(heading As String, shtName As String) As Long
' Return the column number with named header text'
' on given worksheet.
Dim r As Range
Dim wks As Worksheet
Debug.Print shtName
'Exit Function
Set wks = Sheets(shtName)
wks.Range("1:1").Select
With wks
r = .Range("1:1").Find(heading, LookIn:=xlValue)
If r Is Nothing Then
namedColumnNo = -1
Else: namedColumnNo = r.Column
End If
End With
End Function
I am using this test sub to call the funtion:
Public Sub getCol()
Debug.Print "Find MidTemp on " & DataSht.RawDataSht
Debug.Print "Col " & namedColumnNo("MidTemp", DataSht.RawDataSht)
End Sub
I have a user defined type DataSht where I have variables to name worksheets e.g.
Public Type dataShtNames
HeaderSht As String
RawDataSht As String
ResultDataSht As String
End Type
Public DataSht As dataShtNames
With the Exit Function statement uncommented the variables resolve OK with the debug.print statements I get
Find MidTemp on RawData
RawData:MidTemp
Col 0
Leaving the function to run through the error occurs at
Set wks = Sheets(shtName)
If I replace the argument shtName with the actual sheet name as a string "RawData", then the error moves down to the line using the second argument heading. If I substitute a the parameter with a string here the error persists.
Is there something I am missing here? Some help will be much appreciated.
Sadly can't comment, but you're actually getting the out of range error because it should be LookIn:=xlValues where you have LookIn:=xlValue
As #Mathieu indicates, you'll need to fix add Set r = Find(heading, LookIn:=xlValues) to set the range to the value returned.
As a side note-you should drop the selection. Its not doing anything for you.
With wks.Range("1:1")
Set r = .Find(heading, LookIn:=xlValues)
If r Is Nothing Then
namedColumnNo = -1
Else: namedColumnNo = r.Column
End If
End With

Excel vba Compile error - Argument not optional,

I'm trying to figure this out and can't.
I keep getting an error: "Compile error - Argument not optional". I am supplying the arguments and they are set as Optional!
Trying to pass a string and an array to a function and count occurrences of the array strings within the string passed.
Code stops running at the line:
Public Function countTextInText(Optional text As String, Optional toCountARR As Variant) As Integer
with a "Compile error: Argument not optional" message highlighting the Val in the line:
For Each Val In toCountARR
Full code:
Private Sub Worksheet_Change(ByVal Target As Range)
Dim nameR As Range
Dim colR As Range
Dim TKRcnt As Integer
Dim TKRarr() As Variant
TKRarr = Array("TKR", "THR", "Bipolar")
Dim ORIFcnt As Integer
Dim ORIFarr() As Variant
TKRarr = Array("ORIF", "Ilizarov", "PFN")
Set nameR = Range("P2:P9")
Set colR = Range("B2:B50,G2:G50,L2:L50")
For Each namecell In nameR
For Each entrycell In colR
If entrycell.text = namecell.text Then
TKRcnt = countTextInText(entrycell.Offset(0, 2).text, TKRarr)
ORIFcnt = countTextInText(entrycell.Offset(0, 2).text, TKRarr)
End If
Next entrycell
MsgBox (namecell.text & " TKR count: " & TKRcnt & " ORIF count: " & ORIFcnt)
Next namecell
End Sub
Public Function countTextInText(Optional text As String, Optional toCountARR As Variant) As Integer
Dim cnt As Integer
Dim inStrLoc As Integer
For Each Val In toCountARR
inStrLoc = InStr(1, text, Val)
While inStrLoc <> 0
inStrLoc = InStr(inStrLoc, text, Val)
cnt = cnt + 1
Wend
Next Val
Set countTextInText = cnt
End Function
Val is a VBA function which requires a single, mandatory, argument - therefore the compiler generates the message saying "Argument not optional" if you don't provide that argument. (MSDN documentation of Val)
It is a bad idea to use VBA function names as variable names, so I would recommend you don't use Val as a variable name - use myVal or anything else that VBA hasn't already used.
If you really want to use Val (and you are sure that you won't be needing to access the Val function at all), you can use it as a variable name if you simply declare it as such, e.g.
Dim Val As Variant
You will also have problems with your line saying
Set countTextInText = cnt
as countTextInText has been declared to be an Integer, and Set should only be used when setting a variable to be a reference to an object. So that line should be
countTextInText = cnt
For those coming late to this question because of the question's title, as I did, having received this error while using the .Find method -
In my case, the problem was that the variable I was Seting was not Dimd at top of function.
My Example
Sub MyTest()
Dim tst, rngAll
rngAll = [a1].CurrentRegion
tst = fnFix1Plus1InValues(ByVal rngAll As Range)
End Sub
Public Function fnFix1Plus1InValues(ByVal rngAll As Range) As Boolean
Dim t1, t2, arr, Loc '<=== Needed Loc added here
Set Loc = rngAll.Find(What:="+", LookIn:=xlValues, LookAt:=xlPart, MatchCase:=False)
If Not Loc Is Nothing Then
Do Until Loc Is Nothing
t1 = Loc.Value
If fnContains(t1, "+") Then
'Do my stuff
End If
Set Loc = rngAll.FindNext(Loc)
Loop
End If
End Function 'fnFix1Plus1InValues

Can I Evaluate An Excel VB Constant That Is In String Format?

Is it possible to Evaluate a String which contains a valid Excel VB Constant's Name
to return that Constant's Value?
eg
Dim ConstantName as String
Dim ConstantValue as Long
ConstantName="xlValues"
ConstantValue= UnknownFunction(ConstantName)
'would set ConstantValue=-4163
Fun!
Option Explicit
Function getConstantValue(constStr As String) As Variant
Dim oMod As VBIDE.CodeModule
Dim i As Long, _
num As Long
Set oMod = ThisWorkbook.VBProject.VBComponents("Module1").CodeModule
For i = 1 To oMod.CountOfLines
If oMod.Lines(i, 1) = "Function tempGetConstValue() As Variant" Then
num = i + 1
Exit For
End If
Next i
oMod.InsertLines num, "tempGetConstValue = " & constStr
getConstantValue = Application.Run("tempGetConstValue")
oMod.DeleteLines num
End Function
Function tempGetConstValue() As Variant
End Function
All code must be in a module called Module1. That can be changed pretty simply by changing the text "Module1" in the routine.
You'll need to add a reference to Microsoft Visual Basic for Applications Extensibility x.x
There are a number of ways this could fail. Let me know if you have any problems with it :)
Instead of using constants, you could use a dictionary
Dim dict As Object
Sub InitialiseDict()
Set dict = CreateObject(Scripting.Dictionary)
dict("xlValues") = -4163
dict("const1") = value1
...
dict("constN") = valueN
End Sub
ConstValue = dict("xlValues")
Is using the string value necessary?
Dim anyConstant as Long
anyConstant = xlValues
msgbox anyConstant
Set anyConstant to any xl constant you please, they are all enumerated Long values.
The first solution offered is indeed much more fun however.

Resources