How to bypass sql connection error with simple msgbox - sql

Preparing the connection check to the SQL sever, which gives me below error if not in our group network its obsoletely fine but simple msgbox sufficient for me
enter image description here
Sub ADOExcelSQLServer()
Dim Cn As ADODB.connection
Dim server_name As String
Dim database_name As String
Dim User_ID As String
Dim Password As String
Dim SQLStr As String
Dim rs As ADODB.Recordset
Dim ws As Worksheet
Set rs = New ADODB.Recordset
Set ws = ActiveSheet
server_name = "192.168.x.xxx\SQLEXPRESS"
database_name = "ABC_System"
User_ID = "xx"
Password = "12345"
SQLStr = "SELECT * FROM dbo.Tbl_anb"
'SQLStr = "dbo.Tbl_wid"
Set Cn = New ADODB.connection
Cn.Open "Driver={SQL Server};Server=" & server_name & ";Database=" & database_name & _
";Uid=" & User_ID & ";Pwd=" & Password & ";"
If Cn.State = 1 Then
Debug.Print "Connected!"
MsgBox "Connected"
Else
MsgBox "Not Connected"
End If

Here is modified version with On error:
Dim Cn As ADODB.connection
Dim server_name As String
Dim database_name As String
Dim User_ID As String
Dim Password As String
Dim SQLStr As String
Dim rs As ADODB.Recordset
Dim ws As Worksheet
Set rs = New ADODB.Recordset
Set ws = ActiveSheet
server_name = "192.168.x.xxx\SQLEXPRESS"
database_name = "ABC_System"
User_ID = "xx"
Password = "12345"
SQLStr = "SELECT * FROM dbo.Tbl_anb"
'SQLStr = "dbo.Tbl_wid"
Set Cn = New ADODB.connection
On error resume next
Cn.Open "Driver={SQL Server};Server=" & server_name & ";Database=" & database_name & _
";Uid=" & User_ID & ";Pwd=" & Password & ";"
on error Goto 0
If Cn.State = 1 Then
Debug.Print "Connected!"
MsgBox "Connected"
Else
MsgBox "Not Connected"
end if

Related

VBA Excel SQL object variable or with block variable not set

Hi I keep getting an error when trying to upload to sql. The code have been working before, but I can find what I missed when rewriting the code..
it is falling at line:
cmd.CommandText = strSQL
the code is pretty simple it takes one column in a sheet and then upload or insert it in to an SQL database. please tell me what code I'm missing, or if I declare something wrong here
Dim cn As ADODB.Connection
Set sTroksheet = ThisWorkbook.Sheets("Mlist")
Set cn = New ADODB.Connection
Dim rs As New ADODB.Recordset
Dim strConn As String
Dim SQLstr As String
Dim SQLstrl As String
Dim Password As String
Dim Server_Name As String
Dim User_ID As String
Dim Database_Name As String
Dim Port_Name As String
Dim strTable As String
Dim excel_row As Long
Dim cmd As ADODB.Command
Dim rst_recordset As ADODB.Recordset
If ThisWorkbook.Sheets("Tournament Settings").Range("D4") = vbNullString
Then
MsgBox "Please setup database connection first in (DB Setup) in top menu"
Exit Sub
Else
Server_Name = Sheets("Software_Setup").Range("c3").Value
Database_Name = Sheets("Software_Setup").Range("c4").Value
User_ID = Sheets("Software_Setup").Range("c5").Value 'id user or username
Password = Sheets("Software_Setup").Range("c6").Value 'Password
Port_Name = Sheets("Software_Setup").Range("c7").Value 'Password
strConn = "Driver={MySQL ODBC 5.3 ANSI Driver};Server=" & _
Server_Name & ";Database=" & Database_Name & _
";Uid=" & User_ID & ";Pwd=" & Password & ";"
cn.Open strConn
LastRow = sTroksheet.Range("A65536").End(xlUp).row
strTable = Database_Name & ".TLHMember_List"
strSQL = "INSERT INTO " & strTable & _
" (Player) VALUES "
strSQL2 = ""
For excel_row = 1 To LastRow
strSQL2 = strSQL2 & _
"('" & sTroksheet.Cells(excel_row, 1) & "') ,"
Next excel_row
strSQL = strSQL & strSQL2
Mid(strSQL, Len(strSQL), 1) = ";" ' gets rid of the last comma
cmd.CommandText = strSQL
cmd.Execute
cn.Close
End If
You need to either change this line:
Dim cmd As ADODB.Command
to
Dim cmd As New ADODB.Command
or just before error line add new line:
Set cmd = new ADODB.Command
cmd.CommandText = strSQL

How to extract the data from SQL Server to Excel using vba?

Sub aa()
Dim conn As ADODB.Connection
Dim rs As ADODB.Recordset
Dim sConnString As String
' Create the connection string.
sConnString = "Provider=SQLOLEDB;Data Source=INSTANCE\SQLEXPRESS;" & _
"Initial Catalog=Raja;" & _
"Integrated Security=SSPI;"
' Create the Connection and Recordset objects.
Set conn = New ADODB.Connection
Set rs = New ADODB.Recordset
' Open the connection and execute.
conn.Open sConnString
Set rs = conn.Execute("SELECT * FROM raja.dbo.saran")
' Check we have data.
If Not rs.EOF Then
' Transfer result.
Sheets(1).Range("A1").CopyFromRecordset rs
' Close the recordset
rs.Close
Else
MsgBox "Error: No records returned.", vbCritical
End If
' Clean up
If CBool(conn.State And adStateOpen) Then conn.Close
Set conn = Nothing
Set rs = Nothing
End Sub
Please find above code but the above code is not working.please how to resolve this issue.
There are so many ways to do this!!
Sub ADOExcelSQLServer()
' Carl SQL Server Connection
'
' FOR THIS CODE TO WORK
' In VBE you need to go Tools References and check Microsoft Active X Data Objects 2.x library
'
Dim Cn As ADODB.Connection
Dim Server_Name As String
Dim Database_Name As String
Dim User_ID As String
Dim Password As String
Dim SQLStr As String
Dim rs As ADODB.Recordset
Set rs = New ADODB.Recordset
Server_Name = "NAME" ' Enter your server name here
Database_Name = "AdventureWorksLT2012" ' Enter your database name here
User_ID = "" ' enter your user ID here
Password = "" ' Enter your password here
SQLStr = "SELECT * FROM [SalesLT].[Customer]" ' Enter your SQL here
Set Cn = New ADODB.Connection
Cn.Open "Driver={SQL Server};Server=" & Server_Name & ";Database=" & Database_Name & _
";Uid=" & User_ID & ";Pwd=" & Password & ";"
rs.Open SQLStr, Cn, adOpenStatic
' Dump to spreadsheet
With Worksheets("sheet1").Range("a1:z500") ' Enter your sheet name and range here
.ClearContents
.CopyFromRecordset rs
End With
' Tidy up
rs.Close
Set rs = Nothing
Cn.Close
Set Cn = Nothing
End Sub
OR . . .
Sub ADOExcelSQLServer()
Dim Cn As ADODB.Connection
Dim Server_Name As String
Dim Database_Name As String
Dim User_ID As String
Dim Password As String
Dim SQLStr As String
Dim rs As ADODB.Recordset
Set rs = New ADODB.Recordset
Server_Name = "Server_Name" ' Enter your server name here
Database_Name = "Northwind" ' Enter your database name here
User_ID = "" ' enter your user ID here
Password = "" ' Enter your password here
SQLStr = "SELECT * FROM Orders" ' Enter your SQL here
Set Cn = New ADODB.Connection
Cn.Open "Driver={SQL Server};Server=" & Server_Name & ";Database=" & Database_Name & _
";Uid=" & User_ID & ";Pwd=" & Password & ";"
rs.Open SQLStr, Cn, adOpenStatic
With Worksheets("Sheet1").Range("A2:Z500")
.ClearContents
.CopyFromRecordset rs
End With
rs.Close
Set rs = Nothing
Cn.Close
Set Cn = Nothing
End Sub
Or . . .
Sub TestMacro()
' Create a connection object.
Dim cnPubs As ADODB.Connection
Set cnPubs = New ADODB.Connection
' Provide the connection string.
Dim strConn As String
'Use the SQL Server OLE DB Provider.
strConn = "PROVIDER=SQLOLEDB;"
'Connect to the Pubs database on the local server.
strConn = strConn & "DATA SOURCE=(local);INITIAL CATALOG=NORTHWIND.MDF;"
'Use an integrated login.
strConn = strConn & " INTEGRATED SECURITY=sspi;"
'Now open the connection.
cnPubs.Open strConn
' Create a recordset object.
Dim rsPubs As ADODB.Recordset
Set rsPubs = New ADODB.Recordset
With rsPubs
' Assign the Connection object.
.ActiveConnection = cnPubs
' Extract the required records.
.Open "SELECT * FROM Categories"
' Copy the records into cell A1 on Sheet1.
Sheet1.Range("A1").CopyFromRecordset rsPubs
' Tidy up
.Close
End With
cnPubs.Close
Set rsPubs = Nothing
Set cnPubs = Nothing
End Sub
Also, check out the links below.
https://www.excel-sql-server.com/excel-import-to-sql-server-using-distributed-queries.htm#Introduction
https://www.excel-sql-server.com/excel-sql-server-import-export-using-vba.htm#Introduction

Insert Data to Excel from SQL Table using a Stored Procedure

I would like to insert data from a SQL Table to an Excel sheet everyday using a stored procedure. It has to delete the data in excel and insert the new data to same sheet.
How do I do this?
I get an error in this code
Sub Connecion()
' Create a connection object.
Dim cnPubs As ADODB.Connection
Set cnPubs = New ADODB.Connection
' Provide the connection string.
Dim strConn As String
'Use the SQL Server OLE DB Provider.
strConn = "PROVIDER=SQLOLEDB;"
'Connect to the Pubs database on the local server.
strConn = strConn & "DATA SOURCE=(10.200.157.110);INITIAL CATALOG=Brickstream_DEVMGR;"
'Use an integrated login.
strConn = strConn & " INTEGRATED SECURITY=sspi;"
'Now open the connection.
cnPubs.Open strConn
End Sub
Below code worked for me
Sub GetDataFromADO()
'Declare variables'
Set objMyConn = New ADODB.Connection
Set objMyRecordset = New ADODB.Recordset
Dim strSQL As String
'Open Connection'
objMyConn.ConnectionString = "Provider=SQLOLEDB;Data Source=10.200.157.110;Initial Catalog=Brickstream_DEVMGR;User ID=usr_bayi;Password=3Ay1usr;"
objMyConn.Open
'Set and Excecute SQL Command'
strSQL = "select * from DEALER_DETAILED"
'Open Recordset'
Set objMyRecordset.ActiveConnection = objMyConn
objMyRecordset.Open strSQL
'Copy Data to Excel'
ActiveSheet.Range("A2").CopyFromRecordset (objMyRecordset)
End Sub
Easy ask.
Sub ADOExcelSQLServer()
Dim Cn As ADODB.Connection
Dim Server_Name As String
Dim Database_Name As String
Dim User_ID As String
Dim Password As String
Dim SQLStr As String
Dim rs As ADODB.Recordset
Set rs = New ADODB.Recordset
Server_Name = "your_server_name" ' Enter your server name here
Database_Name = "Northwind" ' Enter your database name here
User_ID = "" ' enter your user ID here
Password = "" ' Enter your password here
SQLStr = "SELECT * FROM Orders" ' Enter your SQL here
Set Cn = New ADODB.Connection
Cn.Open "Driver={SQL Server};Server=" & Server_Name & ";Database=" & Database_Name & _
";Uid=" & User_ID & ";Pwd=" & Password & ";"
rs.Open SQLStr, Cn, adOpenStatic
With Worksheets("Sheet1").Range("A2:Z500")
.ClearContents
.CopyFromRecordset rs
End With
rs.Close
Set rs = Nothing
Cn.Close
Set Cn = Nothing
End Sub

Unique items from Access to Excel

I have this code:
Dim cn As Object
Dim rs As Object
Dim strSql As String
Dim strConnection As String
Set cn = CreateObject("ADODB.Connection")
strConnection = "Provider=Microsoft.ACE.OLEDB.12.0;" & _
"Data Source=\\lm\central\Permkt\Svc02-User-Disk\Sales\Sales-Private\Consumer Marketing\Marketing Analytics\Testing Framework\2014Data.accdb"
strSql = "SELECT distinct project1 FROM 2014Data"
cn.Open strConnection
Set rs = cn.Execute(strSql)
rw = 1
For Each myfield In rs.Fields
Cells(rw, 7) = myfield
rw = rw + 1
Next myfield
rs.Close
Set rs = Nothing
cn.Close
Set cn = Nothing
End Sub
And now i am getting the first project1 in the cell as a value, but I should have two unique project1's . How would I get to the second?
Thanks so much for the first comments, the SQL is at least now executing but not sending back both project1 items
You have Dim'ed rs,but never Set rs
I did some stuff on running SQL within VBA:
Public Sub GetCn(ByRef dbcon As ADODB.Connection, ByRef dbrs As ADODB.Recordset, _
sqlstr As String, servername As String, dbname As String)
Set dbcon = New ADODB.Connection
dbcon.CursorLocation = adUseClient
dbcon.Open "Provider=SQLNCLI;Server=" & servername & ";Database=" & dbname & ";Trusted_Connection=yes;"
'"PROVIDER=Microsoft.Jet.OLEDB.4.0;Data Source=" & dbfile & ";", _
'usernm , pword
Set dbrs = New ADODB.Recordset
'Debug.Print sqlstr
dbcon.CommandTimeout = 200
Debug.Print sqlstr
dbrs.Open sqlstr, dbcon
End Sub
Public Sub RunSQL(sql As String)
Dim adoconn As ADODB.Connection
Dim adors As ADODB.Recordset
Dim dbname As String
Dim servername As String
servername = Worksheets("DBSettings").Range("B1").value
dbname = Worksheets("DBSettings").Range("B2").value
Call GetCn(adoconn, adors, sql, servername, dbname)
End Sub
Sub OpenDatabaseConnection(ByVal servername As String, ByVal databasename As String, sql As String, myRange As Range)
Dim connectionstring As String
'Dim SQL As String
Dim adoconn As ADODB.Connection
Dim adors As ADODB.Recordset
Dim dbname As String
If servername = "" Then servername = Worksheets("DBSettings").Range("B1").value
If databasename = "" Then databasename = Worksheets("DBSettings").Range("B2").value
Call GetCn(adoconn, adors, sql, servername, databasename)
NrOfRows = adors.RecordCount
myRange.CopyFromRecordset adors
'LOOP DOOR KOLOMMEN en OUTPUT Columns 1 rij hoger
Dim fieldname As String, counter As Integer
counter = 1
Dim StartRange As Range
Set StartRange = myRange.Worksheet.Range("A1")
For Each Field In adors.Fields
StartRange.Cells(1, counter).value = Field.name
counter = counter + 1
Next
adors.Close
adoconn.Close
Set adors = Nothing
Set adoconn = Nothing
Dim sn() As Variant, wsnn As String
wsnn = myRange.Worksheet.name
sn = Array(wsnn)
'Call NameDeletionV3(sn)
'Call CreateName("RawData", CreateRange(Worksheets(sn), CInt(1), GetLastColumn(Worksheets(sn)), CInt(1), GetLastRow(Worksheets(sn))), Worksheets(sn))
'myRange = Worksheets("Q1-old").Range("B1")
End Sub
and then for usage:
Sub SQL_Execute()
Dim sql As String, FromDate As Date, EndDate As Date
sql = "SELECT * FROM TABLENAME"
Dim myRange As Range
Dim sheetname As String: sheetname = "Sheet1"
Worksheets(sheetname).Cells.Delete
Set myRange = Worksheets(sheetname).Range("A2")
Debug.Print sql
Call OpenDatabaseConnection("", "", sql, myRange)
End Sub

MS Access 2010 using ldap authentication

I am trying to do ldap authentication in ms access 2010 using username and password. I cannot seem to figure this out and have tried different codes online but none seem to work. Can anyone help?
The following is what i have taken from here
Function CheckUser(username As String, passwd As String, Level As Integer) As Boolean
On Error GoTo LDAP_Error
username = "sharifu"
passwd = "xxx"
Const ADS_SCOPE_SUBTREE = 2
Dim LDAPPath As String
LDAPPath = "LDAP://172.16.0.12/OU=Sites;DC=domain;DC=com"
Dim conn As ADODB.Connection
Dim cmd As ADODB.Command
Dim rs As ADODB.Recordset
Set conn = New ADODB.Connection
Set cmd = New ADODB.Command
conn.Provider = "ADsDSOObject"
conn.Properties("User ID") = "domain\" & username
conn.Properties("Password") = "" & passwd
conn.Properties("Encrypt Password") = True
'conn.Properties("ADSI Flag") = 3
conn.Open "Active Directory Provider"
Set cmd.ActiveConnection = conn
cmd.Properties("Page Size") = 1000
cmd.Properties("Searchscope") = ADS_SCOPE_SUBTREE
cmd.CommandText = _
"SELECT Name FROM '" & LDAPPath & "' WHERE " & "objectCategory='user'"
Set rs = cmd.Execute
rs.Close
conn.Close
CheckUser = True
Exit Function
LDAP_Error:
If Err.Number = -2147217911 Then
MsgBox "Incorrect PeopleSoftID or Password!", vbExclamation, "HILDA"
Else
MsgBox "Error : " & Err.Description & " " & Err.Number, vbExclamation, "HILDA"
End If
CheckUser = False
conn.Close
End Function
Error I receive is
"Error: The server is not operational.
-2147217865"
Changed to ip address get following error now
Method 'ActiveConnection' of object '_Command' failed but it might be coming from elsewhere in my code. how would i check if ldap was success?
I have fixed issue.
Function CheckUser(UserName As String, passwd As String, Level As Integer) As Boolean
On Error GoTo LDAP_Error
Const ADS_SCOPE_SUBTREE = 2
Dim LDAPPath As String
LDAPPath = "LDAP://akutan.country.domain.com/OU=Sites;DC=domain;DC=com"
Dim conn As ADODB.Connection
Dim cmd As ADODB.Command
Dim rs As ADODB.Recordset
Set conn = New ADODB.Connection
Set cmd = New ADODB.Command
conn.Provider = "ADsDSOObject"
conn.Properties("User ID") = "xxx\" & UserName
conn.Properties("Password") = "" & passwd
conn.Properties("Encrypt Password") = True
'conn.Properties("ADSI Flag") = 3
conn.Open "Active Directory Provider"
Set cmd.ActiveConnection = conn
cmd.Properties("Page Size") = 1000
cmd.Properties("Searchscope") = ADS_SCOPE_SUBTREE
cmd.CommandText = "SELECT Name FROM '" & LDAPPath & "' WHERE " & "objectCategory='user'"
Set rs = cmd.Execute
rs.Close
conn.Close
CheckUser = True
[TempVars]![CurrentUser] = UserName
Call LogUser([TempVars]![CurrentUser], "Logon")
Exit Function
LDAP_Error:
If Err.Number = -2147217911 Then
MsgBox "Incorrect PeopleSoftID or Password!", vbExclamation, "LDAP Authentication"
Else
MsgBox "Error : " & Err.Description & " " & Err.Number, vbExclamation, "LDAP Authentication"
End If
CheckUser = False
conn.Close
End Function
Making little changes and explaining for understanding this code and a correct functioning:
Added the check if the user exist in the Database.
Changed "OU=Sites" in the LDAP path by "CN=Users".
LDAPPath = "LDAP://replace with IP or DNS name/CN=Users;DC=replace with domain name without .com;DC=replace with com, net or root node name"
In IP or DNS Name you must to specify the server IP or DNS Name.
In the first "DC" you must to specify the Domain Name without .com or .net would be like this "google".
In the second "DC" you must to specify the Domain type for intance "com", you can see this post if you want to know what means
Full example:
LDAPPath = "LDAP://200.201.1.1/CN=Users;DC=google;DC=com"
or
LDAPPath = "LDAP://ldap.google.com/CN=Users;DC=google;DC=com"
In this line: conn.Properties("User ID") = "replace with domain short name\" & userName
conn.Properties("User ID") = "ggle\" & userName
Finaly this the full code:
Function ldapAuth(userName As String, passwd As String, level As Integer) As Boolean
On Error GoTo LDAP_Error
ldapAuth = False
If Not IsNull(userName) And Not IsNull(passwd) Then
'Check if the user exist in DB
Dim db As DAO.Database
Dim rst As DAO.Recordset
Dim qdf As QueryDef
Dim strSQL As String
Set dbs = CurrentDb
strSelect = "SELECT *"
strFrom = " FROM employee"
strWhere = " WHERE user_name = '" & userName & "';"
strSQL = strSelect & strFrom & strWhere
Debug.Print strSQL
Set rst = dbs.OpenRecordset(strSQL, dbOpenDynaset)
'If the recordset is empty, exit.
If rst.EOF Then
MsgBox "The user not exist in the DataBase!!!"
Else
'Check user with LDAP
Const ADS_SCOPE_SUBTREE = 2
Dim LDAPPath As String
LDAPPath = "LDAP://ldap.google.com/CN=Users;DC=google;DC=com"
Dim conn As ADODB.Connection
Dim cmd As ADODB.Command
Dim rs As ADODB.Recordset
Set conn = New ADODB.Connection
Set cmd = New ADODB.Command
conn.Provider = "ADsDSOObject"
conn.Properties("User ID") = "ggle\" & userName
conn.Properties("Password") = "" & passwd
conn.Properties("Encrypt Password") = True
'conn.Properties("ADSI Flag") = 3
conn.Open "Active Directory Provider"
Set cmd.ActiveConnection = conn
cmd.Properties("Page Size") = 1000
cmd.Properties("Searchscope") = ADS_SCOPE_SUBTREE
cmd.CommandText = "SELECT Name FROM '" & LDAPPath & "' WHERE " & "objectCategory='user'"
Set rs = cmd.Execute
rs.Close
conn.Close
'Set userId and Role Globally
employeeId = rst![id]
employeeType = rst![employee_type]
TempVars.Add "employeeId", employeeId
TempVars.Add "employeeType", employeeType
'Log user login and role
Debug.Print "User login: " & TempVars!employeeId
Debug.Print "User Role: " & TempVars!employeeType
ldapAuth = True
rst.Close
End If
End If
Exit Function
LDAP_Error:
If Err.Number = -2147217911 Then
'MsgBox "Incorrect User or Password!", vbExclamation, "LDAP Authentication"
Else
MsgBox "Error : " & Err.Description & " " & Err.Number, vbExclamation, "LDAP Authentication"
End If
conn.Close
End Function