0

I want to input username and password SQL Server from userform VBA Excel, but I don't understand how to do that. So I create code like this:

Sub OPenCOnn()    
   Set cnn = New ADODB.Connection
   cnn.ConnectionString = "Provider=SQLOLEDB;Data Source=172.20.20.20;Initial Catalog=bank;User ID=" & txtUser.Text & ";Password=" & txtPass.Text & ";"
End Sub

But its didn't work. I receive the below error:

run time error, object required

5
  • 2
    What does "it didn't work" mean? Why didn't it work? What error or unexpected behaviour did you get? Commented Sep 13, 2019 at 10:08
  • how the correct code should be? Commented Sep 13, 2019 at 10:24
  • "how the correct code should be?" That doesn't look like an error. If you are getting a prompt like that, it's coming from your own code that you've omitted from your post. Commented Sep 13, 2019 at 10:24
  • how to input text/value to 'User ID=' and 'Password=' from userform? Commented Sep 13, 2019 at 10:28
  • At what point does that error occur, I'm guessing at Set cnn = New ADODB.Connection? Commented Sep 13, 2019 at 10:33

2 Answers 2

2

You need single quotes around the strings like this:

cnn.ConnectionString = "Provider=SQLOLEDB;Data Source=172.20.20.20;Initial Catalog=bank;User ID='" & txtUser.Text & "';Password='" & txtPass.Text & "';"
Sign up to request clarification or add additional context in comments.

1 Comment

That's not necessary. Quoting is only needed if the username or passwords themselves contains quotes
0

run time error, object required

You are getting that error because your code cannot find txtUser and txtPass

Ensure the textboxes are there.

enter image description here

Use Option Explicit on the top of your code and then you will notice that it will highlight txtUser and say that Variable not defined. Of Course you will have to also define cnn as Dim cnn As ADODB.Connection

enter image description here

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.