Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
596 views
in Technique[技术] by (71.8m points)

excel - How to set textbox value to variable to use in match function VBA

I want to let a user input a string into a text box on a user form. I then want to compare that value to a range in a table.

I try to set the textbox value to a variable and it tells me I an "Object is required".

Private Sub CommandButton1_Click()
Dim NwIns As TextBox
Dim tblm As Range
Dim c As TextBox

Set tblm = Worksheets("Main Committee Database").ListObjects("CredDB").ListColumns(3).DataBodyRange
UserForm1.TextBox1.SetFocus
Set c = UserForm1.TextBox1.Value

If IsNumeric(Application.WorksheetFunction.Match(c, tblm, 0)) = True Then

MsgBox "This Vendor Already Exists"

Else
question from:https://stackoverflow.com/questions/65904450/how-to-set-textbox-value-to-variable-to-use-in-match-function-vba

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

If you want C as a textbox you can't assign a string value to it.

Dim c as Control
Set c = UserForm1.Controls("TextBox1")

Or you could do

Dim c as string
c = UserForm1.TextBox1

But if you want to do anything to that textbox, like clear it after, it's best to just get the object itself instead of the value.

application.worksheetfunction.match will error if doesn't match. You could use error handling instead of your if statement but that isn't a great way to deal with it. A better way is to use .find and then check if it actually found anything.

All together:

Private Sub CommandButton1_Click()
Dim NwIns As TextBox
Dim tblm As Range
Dim c As Control
Dim fndrng As Range

Set tblm = Worksheets("Main Committee Database").ListObjects("CredDB").ListColumns(3).DataBodyRange
UserForm1.TextBox1.SetFocus

Set c = UserForm1.Controls("TextBox1")
Set fndrng = tblm.Find(c.Value, LookIn:=xlValues, lookat:=xlWhole) 'You may want to play with those parameters to meet your needs.

If Not fndrng Is Nothing Then
    MsgBox "This Vendor Already Exists"

Else

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...