Changing of DSN in VBA - vba

I am trying to change the connection of the excel from JDE to SQL Server 2014. How/What should i do/change in order to connect to another DSN in my ODBC.
This is my code for cnnStr:
uid = Range("P_Uid")
pwd = Range("P_Pwd")
dsn = Range("P_Dsn")
cnnstr = "ODBC;DSN=" + dsn + ";UID=" + uid + ";PWD=" + pwd
This is the original code from VBA:
Dim strCnn As String
Dim i As Long
Dim y As Long
Dim j As Long
Dim z As Double
Dim w As Double
Dim Wks As DAO.Workspace
Dim Cnn As DAO.Connection
Dim Qdf As DAO.QueryDef
Dim Rec As DAO.Recordset
Dim date1, date2 As String
Dim x As Long
Dim w_price As Double
Dim w_amt As Double
Dim w_qty As Long
Dim Xref_Name(10) As Variant
Set Rec = Nothing
Set Wks = CreateWorkspace("WKSTmp", "", "", dbUseODBC)
Set Cnn = Wks.OpenConnection("", dbDriverNoPrompt, True, cnnstr)
Cnn.QueryTimeout = 1800
Set Rec = Cnn.OpenRecordset(SQL)
avarow = Worksheets("Ava").UsedRange.Rows.Count
Whenever i mouse over to cnnstr, i will see this code :
cnnstr = "ODBC;DSN=JDE;UID=abc;PWD=abc"
The DSN is always JDE even though i have tried to change the connection and the cnnStr above.
The details of the cnnstr is taken from a control sheet within the excel file. Changes made to the control sheet proved futile.
Please advice on how I can change the dsn so that I can get the data from SQL Server 2014.

This is what I use use to connect to SQL server 2014,
Code,
Sub ConnectSQLServer()
Dim conn As ADODB.Connection
Dim rs As ADODB.Recordset
Dim sConnString As String
sConnString = "PROVIDER=SQLOLEDB;" & _
"Data Source=xxx.xxx.x.xxx,1433;" & _
"Initial Catalog=Staff_Manager;" & _
"User Id=sa;" & _
"Password=myPassword;"
Set conn = New ADODB.Connection
Set rs = New ADODB.Recordset
conn.Open sConnString
Set rs.ActiveConnection = conn
Set rs.ActiveConnection = conn
strSQL = "SELECT Your SQL Statement "
rs.Open strSQL
If that is what you are trying to achieve this will work.

Assuming you didn't leave out anything important from your original code, cnnstr is neither a local declared variable, nor is it assigned in that routine. Most likely you either have a cnnstr() function or it's a global variable being set in the CreateWorkspace() function.
The simplest way to find where the code is still assigning the old connection string to cnnstr is to use Find to search the Current Project for "cnnstr =". (Minus the quotes.) Make sure you are searching Current Project in case the assignment is happening in a different module.

Related

How do I make a db connection to Excel that more than one user can open at same time?

You've help me to get to this point and now I'm stuck again. The macro works fine, but only one person can run it at any given time. If two users try to run it at the same time, they get a Runtime error. When I click Debug, it takes me to "myConn.Open"
To clarify, I'm not trying to allow multiple users to edit the Excel spreadsheet. They are only opening it read-only to get values from it, not to add or edit it in any way.
Public Sub Letter()
Dim rngStory As Word.Range
Dim rngCount As Long
Dim mySQLquery As String
Dim myKey As String
Dim mySource As String
Dim slkAddresseeName, slkRegarding, slkFileNum, slkSalutation As String
Dim slkTemplate As String
Dim myConn As ADODB.Connection
Dim myRs As ADODB.Recordset
Dim slkTempDoc As String
' Prompt user for Login ID
myKey = InputBox("Enter Attorney or Paralegal LOGIN ID (e.g., jtorres or b324):")
' Make DB connection
mySQLquery = "SELECT * FROM [All_Users$] WHERE LoginID = '" & myKey & "'"
mySource = "\\servername\vol1\macros\master\LetterMemoDB.xlsx"
Set myConn = New ADODB.Connection
Set myRs = New ADODB.Recordset
With myConn
.Provider = "Microsoft.ACE.OLEDB.12.0;Data Source=" & mySource & ";Extended Properties=""Excel 8.0;HDR=YES"";"
End With
myConn.Open
myRs.Open mySQLquery, myConn, adOpenStatic, adLockReadOnly
' End of DB connections
My guess is I'm using ACE as the provider and maybe it can't support multiple, simultaneous connections. What's the fix?
Fix was to change the Excel file to read-only via right click | Properties. Sorry for the stupid question.

VBA(AUTOCAD) SQL query to store String Values

I have a small issue, I am trying to code a Macro for Autocad in VBA.
I am trying to read a certain column value through sending a SQL native query that connects to the database server.
The problem is that my String variable descToReturn that's going to hold a value of that column is returning null. I can't seem to figure out where I am wrong. So if anyone can advise that'd be great.
Here's the code below:
Private Sub btnDuplicate_Click()
Dim cnn As ADODB.Connection
Dim rst As ADODB.Recordset
Dim ConnectionString As String
Dim StrQuery As String
Dim BOMLineToCheck As AcadBlockReference
Dim BOMAttributes As Variant
Dim partNoToCheck As String
Dim i As Integer
Dim descToReturn As String
ConnectionString = "Provider=SQLxxxxx.1;Password=xxxx;Persist Security Info=True;User ID=xxxx;Data Source=xx\xx;Use Procedure for Prepare=1;Auto Translate=True;Packet Size=4096;Use Encryption for Data=False;Tag with column collation when possible=False;Initial Catalog=xxx_xxx"
Set cnn = New ADODB.Connection
cnn.ConnectionString = ConnectionString
cnn.Open
'cnn.CommandTimeout = 900
Set rst = New ADODB.Recordset
StrQuery = "SELECT * FROM [My Table Name] WHERE [My Column]='partNoToCheck'"
For Each BOMLineToCheck In ThisDrawing.ModelSpace
If BOMLineToCheck.Name = "BOM3LINE_old" Then
BOMAttributes = BOMLineToCheck.GetAttributes()
For i = 0 To UBound(BOMAttributes)
If BOMAttributes(i).TagString = "PART#" Then
partNoToCheck = BOMAttributes(i).TextString
End If
Next i
End If
rst.Open StrQuery, cnn, adOpenDynamic
With rst
If Not .EOF Then
descToReturn = rst![My Coulmn]
End If
End With
rst.Close
MsgBox descToReturn
Next
End Sub
Look closely for a typo:
descToReturn = rst![My Coulmn]
You probably mean:
descToReturn = rst![My Column]
See the difference?
So, I found the answer, because I am bringing SQL within VBA environment, the syntax was not right and its a weird syntax:
correct Syntax for SQL query:
StrQuery = "SELECT * FROM [My Table] WHERE [My Column]= '" & partNoToCheck & "'"

Is there a limit to the query length being passed to ADODB?

I am currently testing a framework that stores a SQL query in a cell on an excel workbook and then passes the cell value to a variable. This variable then gets executed through rs.Open query, cn where:
Dim rs As ADODB.Recordset
Dim cn As ADODB.Connection
and I have tried these for "query" :
Dim query as String
Dim query as Variant
or even playing with fixed length queries:
Dim query as String * 9999
In playing with the output of the query string, it cuts off somewhere around 8000. Google is coming up short for me, so I am coming here for answers. Is there a specific limit to what a variable can pass to recordset.Open()?
NB: The connection string I am using for this particular query is :
ConnectionString = "User ID=User;Password=PW;Data Source=DB;Provider=OraOLEDB.Oracle"
But if you know whether there is a system specific limit for Oracle, NetezzaSQL, or MS SQL Server (SQLOLEDB.1) please let me know. I will need to specify the limitations of each in order to define which new queries will need to be converted into stored procedures.
Here is the essentials of the code:
Sub RunQueryTable()
Dim cn As ADODB.Connection
Dim RS As ADODB.Recordset
Dim iCols As Integer
Dim DB As String, User As String, PW As String
Dim SQLTable As Worksheet
Dim ConnectionString as String
Dim query As String 'Or Dim query As Variant 'Or Dim query As String * 9999
Dim i As Long
etc, etc.
Set SQLTable = Sheet32
Set cn = New ADODB.Connection
Set RS = New ADODB.Recordset
DB = _____
User = ______
PW = ____
ConnectionString = "User ID=" & User & _
";Password=" & PW & _
";Data Source=" & DB & _
";Provider=OraOLEDB.Oracle"
query = SQLTable.Cells(i, 3).Text
cn.Open (ConnectionString)
RS.CursorType = adOpenForwardOnly
RS.Open (query), cn
For iCols = 0 To RS.Fields.count - 1
Worksheets("Output").Cells(1, iCols + 1).Value = RS.Fields(iCols).Name
Next
Worksheets("Output").Cells(2, "A").CopyFromRecordset RS
RS.Close
cn.Close
End Sub
The specific error I am getting from VBA is : "ORA-00923: FROM keyword not found where expected" because the query is getting cut off.
Here's your problem:
query = SQLTable.Cells(i, 3).Text
Consider:
Range("A1").Value=string(12000,"*")
? len(range("a1").value) '>> 12000
? len(range("a1").text) '>> 8221

How to connect to Netezza (PureData System for Analytics) via VBA

I am trying to connect to connect to Netezza using VBA. I have enabled the following:
Microsoft Excel 15.0 Object Library
Microsoft Office 15.0 Object Library
Microsoft ActiveX Data Objects 6.1 Library
Visual Basic for Applications
Here is my code:
Sub NZConn()
Dim cmd As New ADODB.Command
Dim rs As New ADODB.Recordset
Dim x As Variant
Set cmd = New ADODB.Command
Set RS = New ADODB.Recordset
cmd.ActiveConnection = "Driver={Netezza " & _
"ODBC};servername=servername;port=####;database=database;" & _
"username=username;password=password;"
cmd.ActiveConnection.CursorLocation = adUseClient
cmd.CommandTimeout = 120
cmd.CommandType = adCmdText
x = "Write Query here"
cmd.CommandText = x
Set rs = cmd.Execute
Sheet1.Range("A1").CopyFromRecordset rs
cmd.ActiveConnection.Close
End Sub
I can get the code to run without throwing back an error, but there is nothing that is pasted from the record set, which leads me to believe that is may have something to do with the structure of the connection string.
I have the server, user id, password, database, port, and driver.
Would I need to establish / open an ActiveConnection first?
I was able to figure out the issue on my own. I found that there is a command line builder in the 'Tools' tab in Aginity, which helped specify the exact connection string I needed to connect to Netezza. Once I had this connection string, I was getting an 'architecture mismatch' error. After downloading the 32-bit ODBC drivers for Netezza, the methodology worked perfectly. Here is the updated code below:
Dim cn As ADODB.Connection
Dim rs As ADODB.Recordset
Dim iCols As Integer
Dim DB As String, User As String, PW As String, ConnectionString As String
Dim Server As String, Query As String
Dim SQLTable As Worksheet
Set cn = New ADODB.Connection
Set rs = New ADODB.Recordset
Set SQLTable = Sheet1
Server = SQLTable.Cells(2,3).Value
User = SQLTable.Cells(2,4).Value
PW = SQLTable.Cells(2,5).Value
DB = SQLTable.Cells(2,6).Value
Query = SQLTable.Cells(2,7).Value
ConnectionString = "Driver={NetezzaSQL};" & _
"server=" & Server & ";" & _
"UserName=" & User & ";" & _
"Password=" & PW & ";" & _
"Database=" & DB & ";" & _
"Query Timeout=120"
cn.Open (ConnectionString)
rs.Open (Query), cn
For iCols = 0 To RS.Fields.count - 1
Worksheets("Sheet2").Cells(1, iCols + 1).Value = rs.Fields(iCols).Name
Next
Worksheets("Sheet2").Cells(2, "A").CopyFromRecordset rs
rs.Close
cn.Close
NB:
"IBM NETEZZA ODBC DRIVER – 32 BIT" is what I downloaded
"ODBC-DRIVER-FOR-NETEZZA-7-X86" is what showed up in my software center to install
"Name: NetezzaSQL ; Version: 7.00.04.41188 ; Company: www.ibm.com ; File: NSQLODBC.DLL" is what is shown now in my 32-bit 'ODBC Data Source Administrator' window
I think your connection string is ok, and yes you should need to open a connection first.
Like this:
AccessConnect = "Driver={Netezza " & _
"ODBC};servername=servername;port=####;database=database;" & _
"username=username;password=password;"
Dim Conn1 As New adodb.Connection
Conn1.ConnectionString = AccessConnect
Conn1.Open
then it would be
Set RS = Conn1.Execute(x) 'where x is your query

Use SQL Statement in access 2007 [duplicate]

What's wrong with this code:
Visual Basic 6.0 With access 2007
Private Sub Command1_Click()
Dim Sell_tbl, Stock_Bottle, res As String
Sell_tbl = "SELECT Sum((Quantity)*12) FROM Sell_Detail Where Cateogry='Large'"
Stock_Bottle = "Select Sum(No_Of_Bottle) FROM Add_Bottle Where Cateogry='Large'"
res = ((Sell_tbl) - (Stock_Bottle))
Adodc1.RecordSource = Sell_tbl
Adodc1.Refresh
Adodc1.Caption = Adodc1.RecordSource
End Sub
Type Mismatch Error
I try to convert its result in other data type but it doesn't work. Can anyone help me?
Neither of these is a recordset, each is a string:
Sell_tbl = "SELECT Sum((Quantity)*12) FROM Sell_Detail Where Cateogry='Large'"
Stock_Bottle = "Select Sum(No_Of_Bottle) FROM Add_Bottle Where Cateogry='Large'"
You need something on the lines of:
Dim Sell_tbl As DAO.Recordset
Dim Stock_Bottle As DAO.Recordset
Set Sell_tbl = CurrentDB.Openrecordset _
("SELECT Sum((Quantity)*12) As Qty FROM Sell_Detail Where Cateogry='Large'")
Set Stock_Bottle = CurrentDB.Openrecordset _
("Select Sum(No_Of_Bottle) As Btl FROM Add_Bottle Where Cateogry='Large'")
res = Sell_tbl!Qty - Stock_Bottle!Btl
The above is a rough outline, it could do with tidying up.
The reason for the error is because of statement:
s = ((Sell_tbl) - (Stock_Bottle))
If you look above that line, you are setting two string variables to SQL -- which is text not numeric.
You need to open recordsets with those sql strings, then get the results, then perform the math.
It is what I want....
Private Sub Command2_Click()
Dim con As New ADODB.Connection
con.Open "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" _
& App.Path & "\add_entry.mdb;Persist Security Info=False"
Dim rs As New ADODB.Recordset
Dim rs1 As New ADODB.Recordset
Dim result_hold As Integer
Dim large_tbl As String
Dim sell_large As String
large_tbl = "SELECT Sum(No_Of_Bottle) FROM add_cotton where Cateogry='Large'"
sell_large = "SELECT Sum(Quantity) FROM Sell_Detail where Cateogry='Large'"
rs.Open large_tbl, con, adOpenDynamic, adLockOptimistic
rs1.Open sell_large, con, adOpenDynamic, adLockOptimistic
result_hold = CInt(rs.Fields(0).Value) - CInt(rs1.Fields(0).Value)
Text1.Text = CStr(result_hold)
End Sub
'if u need to retreive whole colum use loop or etc.. but one thing is remember to you two sources
'never attach with single grid...