Variable type used in VBA Find method

tdbuzz

New Member
Joined
Oct 22, 2015
Messages
2
I'm using Excel 2013 with Windows 7.
I have a user form with a text box named 'TextBox_SearchValue' that accepts a user entered search string. The form also has one button to begin the search. If I use the SearchStartLocation variable as an argument value for 'After:=' in my Find method (as in the below code), it results in error message "Run-time error '13': Type mismatch".
If, however, I hard code "Cells(1, 1)" or "ActiveCell" as a value for 'After:=' the Find method runs without error.
Why is the SearchStartLocation variable not being accepted?

Private SearchStartLocation As String


Private Sub UserForm_Initialize()
SearchStartLocation = "Cells(1, 1)"
End Sub


Private Sub SearchButton_Click()
Cells.Find(What:=TextBox_SearchValue.Text, After:=SearchStartLocation, LookIn:=xlFormulas, _
LookAt:=xlPart, SearchOrder:=xlByRows, SearchDirection:=xlNext, _
MatchCase:=False, SearchFormat:=False).Activate
SearchStartLocation = "ActiveCell"
End Sub
 

Excel Facts

Test for Multiple Conditions in IF?
Use AND(test, test, test, test) or OR(test, test, test, ...) as the logical_test argument of IF.
Your SearchStartLocation variable is a string. The After:= attribute expects a range. Try the following:
Code:
Private SearchStartLocation As Range

Private Sub UserForm_Initialize()
 Set SearchStartLocation = Cells(1, 1)
End Sub


Private Sub SearchButton_Click()
 Cells.Find(What:=TextBox_SearchValue.Text, After:=SearchStartLocation, LookIn:=xlFormulas, _
 LookAt:=xlPart, SearchOrder:=xlByRows, SearchDirection:=xlNext, _
 MatchCase:=False, SearchFormat:=False).Activate
 Set SearchStartLocation = ActiveCell
End Sub
 
Upvote 0
Perfect solution. Using the Range type works just fine, and I learned that Set needs to be used with it too.
Thank you.
 
Upvote 0

Forum statistics

Threads
1,214,621
Messages
6,120,568
Members
448,972
Latest member
Shantanu2024

We've detected that you are using an adblocker.

We have a great community of people providing Excel help here, but the hosting costs are enormous. You can help keep this site running by allowing ads on MrExcel.com.
Allow Ads at MrExcel

Which adblocker are you using?

Disable AdBlock

Follow these easy steps to disable AdBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the icon in the browser’s toolbar.
2)Click on the "Pause on this site" option.
Go back

Disable AdBlock Plus

Follow these easy steps to disable AdBlock Plus

1)Click on the icon in the browser’s toolbar.
2)Click on the toggle to disable it for "mrexcel.com".
Go back

Disable uBlock Origin

Follow these easy steps to disable uBlock Origin

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back

Disable uBlock

Follow these easy steps to disable uBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back
Back
Top