I have an old program I'm looking to convert from VB6 to VB.NET
Here's the code:
Dim cnn As ADODB.Connection
Set cnn = New ADODB.Connection
Dim rs As New ADODB.Recordset
cnn.CursorLocation = adUseClient
cnn.ConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & App.Path & "\TestDB.mdb" & "; Persist Security Info=False;"
cnn.Open
rs.Open "SELECT Addresses.*, Accounts.[Login Status], * FROM Accounts INNER JOIN Addresses ON Accounts.AccountID = Addresses.AccountID WHERE (((Accounts.[Login Status])=Yes))", cnn, adOpenStatic, adLockReadOnly
rs.AbsolutePosition = 1
lblFirstName.Caption = rs![Addresses.First Name]
lblLastName.Caption = rs![Addresses.Last Name]
lblAddress.Caption = rs![Address]
lblPSPR.Caption = rs![Parish/State/Province/Region]
lblZipCode.Caption = rs![Zip Code]
lblCountry.Caption = rs![Country]
lblTelephoneNumber.Caption = rs![Addresses.Telephone Number]
lblCellNumber.Caption = rs![Addresses.Cell Number]
lblAddressID.Caption = rs![AddressID]
cnn.Close
Now the code I here passes the sql result to the labels mentioned above and by changing the rs.AbosolutePosition i can either display the 1st row, 2nd row, 3rd row etc. Now my question is how to i accomplish this in VB.NET ?
Related
I have a csv containing lengthy numbers (like 3-4 billions) which i would like to insert them into access database through ADOBD sql in excel. The code works through but all these numbers become empty when i open the Table in the Access database.
I have double checked in the Designed View in Access that the data type is "Double" in the access and I have no clue why the lengthy intergers will be lost. Can I ask for your guidance on this please? The code has been simplified but the key point is how i could do something on the INSERT INTO line to force it reading lengthy numbers into access database? Many thanks.
Dim cnn As ADODB.Connection
Dim cmd As ADODB.Command
Dim rst As ADODB.Recordset
Dim MyConn
Dim strSQL, strSQL2, strSWL3 As String
Dim InsertDate As Date
Dim FileDate As String
Set cnn = New ADODB.Connection
MyConn = ThisWorkbook.Path & Application.PathSeparator & TARGET_DB
Set cnn = New ADODB.Connection
With cnn
.Provider = "Microsoft.ACE.OLEDB.12.0"
.Open MyConn
End With
Set cmd = New ADODB.Command
Set cmd.ActiveConnection = cnn
Set rst = New ADODB.Recordset
rst.Open "SELECT [Date] FROM [Text;DATABASE=C:\].[Source.csv];", cnn, adOpenDynamic, adLockOptimistic
strSQL = "INSERT INTO [Daily] "
strSQL = strSQL & "SELECT [Date] As WDate, Code, [#Sold] As QtySold"
strSQL = strSQL & " FROM [Text;DATABASE=C:\].[TargetDB.csv]"
cmd.CommandText = strSQL
cmd.Execute
Set cmd = Nothing
rst.Close
Set rst = Nothing
cnn.Close
Set cnn = Nothing
I think I have a fairly simple question to answer. The below code works perfectly as is, with an end result of populating 2 of my userform's combo boxes with field data from an Access data base. I still have several more combo boxes to fill with access data. I am looking for a way to loop through multiple SQL statements in a single record set rather than needing to create a new record set for each SQL query. As always, much appreciated.
Const conStrAccess As String = "Provider=Microsoft.ACE.OLEDB.12.0;Data
Source=C:\Users\Andy\Desktop\Database\IATC.accdb;Persist Security
Info=False;"
Const providerSQL As String = "SELECT DISTINCT [Provider Name] FROM
tblProvider ORDER BY [Provider Name];"
Const employeeSQL As String = "SELECT DISTINCT [Employee Name] FROM
tblEmployee ORDER BY [Employee Name];"
Dim aConn As ADODB.Connection
Dim providerData As ADODB.Recordset
Dim employeeData As ADODB.Recordset
Set aConn = New ADODB.Connection
Set providerData = New ADODB.Recordset
Set employeeData = New ADODB.Recordset
aConn.ConnectionString = conStrAccess
aConn.Open
aConn.ConnectionString = conStrAccess
aConn.Open
providerData.Open providerSQL, aConn, adOpenStatic, adLockReadOnly
providerData.MoveFirst
With Me.cbxProvider
.Clear
Do
.AddItem providerData![Provider Name]
providerData.MoveNext
Loop Until providerData.EOF
End With
employeeData.Open employeeSQL, aConn, adOpenStatic, adLockReadOnly
employeeData.MoveFirst
With Me.cbxEmployee
.Clear
Do
.AddItem employeeData![Employee Name]
employeeData.MoveNext
Loop Until employeeData.EOF
End With
Consider not using any recordsets at all as MS Access form comboboxes and listboxes can use tables and queries as rowsources:
Dim var As Variant, varList As Variant
varList = Array("Provider", "Employee")
For Each var in varList
sql = "SELECT DISTINCT [" & var & " Name] " _
& " FROM tbl" & var & " ORDER BY [" & var & " Name];"
With Me.Form.Controls("cbx" & var)
.RowSourceType = "Table/Query"
.RowSource = sql
.Requery
End With
Next var
In programming a useful rule of thumb is "don't repeat yourself" ("DRY"). If you find you're writing the same code over and over with consistent variations, then you should refactor that code out into a separate method, with some parameters to manage the variations.
Untested:
Sub Main()
Const conStrAccess As String = "Provider=Microsoft.ACE.OLEDB.12.0;Data " & _
"Source=C:\Users\Andy\Desktop\Database\IATC.accdb;Persist Security Info=False;"
Const providerSQL As String = "SELECT DISTINCT [Provider Name] FROM tblProvider ORDER BY [Provider Name]"
Const employeeSQL As String = "SELECT DISTINCT [Employee Name] FROM tblEmployee ORDER BY [Employee Name]"
Dim aConn As New ADODB.Connection
aConn.Open conStrAccess
FillListBox aConn, providerSQL, Me.cbxProvider
FillListBox aConn, employeeSQL, Me.cbxEmployee
'...more lists...
aConn.Close
End Sub
'Fill a combobox from a single-field SQL query
Sub FillComboBox(con As ADODB.Connection, SQL As String, cb)
Dim rs As New ADODB.Recordset
rs.Open SQL, con, adOpenStatic, adLockReadOnly
With cb
.Clear
Do While Not rs.EOF
.AddItem rs.Fields(0).Value
rs.MoveNext
Loop
End With
rs.Close
End Sub
My team and I support a large network of MS access applications. Recently we upgraded our Microsoft Office from 2010 to 2013. The only thing that broke in this upgrade was our ability to sort/filter datasheets that are populated from an ADO RecordSet. Attempting to filter results in an error
Data Provider could not be initialized
From my research I understand that Microsoft considers ADO deprecated and has stopped supporting ADO as a means of populating RecordSets.
I'm however in a specific bind and have been trying every "fix" I could find in order to get this datasheet filterable. I am open to all suggestions.
The closest I have gotten is by populating the datasheet via a stored procedure:
Dim cn As New ADODB.connection
Dim cm As New ADODB.Command
Set cn = New ADODB.connection
With cn
.Provider = "Microsoft.Access.OLEDB.10.0"
.Properties("Data Provider") = "SQLNCLI10"
.Properties("Data Source") = "ascsql2012sbox"
.Properties("Integrated Security") = "SSPI"
.Properties("Initial Catalog") = "assetQuality_dev"
End With
cn.Open
Dim rs As ADODB.recordset
Set rs = New ADODB.recordset
With cm
.ActiveConnection = cn
.CommandText = "dbo.accountIDproc"
.CommandType = adCmdStoredProc
.parameters.Refresh
End With
With rs
.ActiveConnection = cn
.CursorType = adOpenForwardOnly
.CursorLocation = adUseClient
End With
Set rs = cm.Execute
cm.ActiveConnection = Nothing
Set Me.recordset = rs
rs.Close
Set rs = Nothing
cn.Close
Set cn = Nothing
But the same error
Data provider could not be initialized
is still showing up whenever I try to sort a column from A-Z or Z-A. For some columns that contain an integer value. It asks me for a value to sort by then tells me "that's not a valid value" when it's absolutely a valid value.
Thank you for your time.
I ended up answering my own question with a pretty solid solution as suggested by #parfiat
I created a temp table then inserted values from a recordset. I then set the temp table to the DAO.recordset which my datasheet pulls from. Here's my coded solution:
Set rs = New ADODB.recordset
Set cn2 = New ADODB.connection
With cn2
.Provider = "Microsoft.Access.OLEDB.10.0"
.Properties("Data Provider") = "SQLNCLI10"
.Properties("Data Source") = "ascsql2012sbox"
.Properties("Integrated Security") = "SSPI"
.Properties("Initial Catalog") = "assetQuality_dev"
End With
cn2.Open
cn2.CommandTimeout = 0
rs.CursorLocation = adUseClient
rs.LockType = adLockOptimistic
rs.CursorType = adOpenKeyset
rs.Source = "SELECT " & sqlSelect & " FROM " & sqlFrom & IIf(sqlWhere <> "", " WHERE " & sqlWhere, "") & IIf(sqlOrder <> "", " ORDER BY " & sqlOrder, "")
Set rs.ActiveConnection = cn2
rs.Open
If AccessTableExists("ThisTable") = True Then
DoCmd.DeleteObject acTable = acDefault, "ThisTable"
End If
' Create temp table
Dim dbs As Database
' on your computer
Set dbs = CurrentDb
' Create a table with two text fields.
dbs.Execute "CREATE TABLE ThisTable " _
& "(accountID int, customerName CHAR, phoneHome VARCHAR(25), taxID VARCHAR(9), address VARCHAR(200), addressState VARCHAR(2), addressCity VARCHAR(2), bank VARCHAR(35), dateReview VARCHAR(200), orderDateReview VARCHAR(100), dateDue VARCHAR(100), balCustomer VARCHAR(200), activityCode VARCHAR(100), dateActivity VARCHAR(100), accountNumber VARCHAR(25));"
dbs.Close
Dim dbsTemp As DAO.Database
Dim rstemp As DAO.recordset
Set dbsTemp = CurrentDb
Set rstemp = dbsTemp.OpenRecordset("ThisTable", dbOpenDynaset)
Do While Not rs.EOF
rstemp.AddNew
rstemp!accountID.value = rs!accountID.value
rstemp!customerName.value = rs!customerName.value
rstemp!balCustomer.value = rs!balCustomer.value
rstemp!accountNumber.value = rs!accountNumber.value
rstemp!dateDue.value = rs!dateDue.value
rstemp!taxID.value = rs!taxID.value
rstemp!phoneHome.value = rs!phoneHome.value
rstemp!dateReview.value = rs!dateReview.value
rstemp!activityCode.value = rs!activityCode.value
rstemp!dateActivity.value = rs!dateActivity.value
rstemp.update
rs.MoveNext
Loop
Set Me.recordset = rstemp
rs.Close
Set rs = Nothing
cn2.Close
Set cn2 = Nothing
Here's the code
Dim cmd As ADODB.Command
Dim conn As ADODB.Connection
Set conn = New ADODB.Connection
conn.CursorLocation = adUseClient
conn.Open "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & App.Path & "\Nirvana.mdb" & "; Persist Security Info=False;"
Set cmd = New ADODB.Command
cmd.CommandText = "Select [Last Name] From Accounts Where [First Name]=#FN"
Set cmd.ActiveConnection = conn
cmd.Parameters.Item("#FN").Value = txtFirstName.Text
cmd.Execute
Set cmd.ActiveConnection = Nothing
Set cmd = Nothing
conn.Close
How do i pass the result of this query to a variable in Visual Basic 6.0 ?
Results are stored in a Record Set, create one:
dim rs as ADODB.RecordSet
Then instead of cmd.execute use:
rs.open cmd
if not rs.eof then
''//got rows
msgbox "first row, first col=" & rs.collect(0)
...
I am trying to retrieve records saved in MS Access database and populate the textboxes with the query result during FORM_LOAD(). So far I retrieve one record. But the problem is, when I try adding the same codes, it is retrieving the first saved record.
It is disregarding the where clause in my sql statement. Here's what I wanted my output to be. During form_load(), I want to display multiple records (activity description/activity_desc) in multiple textboxes on my form. If there is no record in my database, I just want it to be blank.
Here's what i want to achive..
Here's my code snippet:
Private Sub Form_Load()
FrmSchedule.lblnamesched.Caption = FrmInfosheet.Txtname.Text
FrmSchedule.Label36.Caption = FrmInfosheet.cmbsalesgroup.Text
FrmSchedule.lblpositionsched = FrmInfosheet.Txtposition.Text
FrmSchedule.Thisweekdate.Caption = FrmInfosheet.Text3.Text
FrmSchedule.Thisweekdate2.Caption = FrmInfosheet.Text4.Text
FrmSchedule.Label37.Caption = FrmWeek1WAR.Label1.Caption
FrmSchedule.Label38.Caption = FrmWeek1WAR.Label2.Caption
FrmSchedule.Label39.Caption = FrmWeek1WAR.Label21.Caption
FrmSchedule.Label40.Caption = FrmWeek1WAR.Label22.Caption
FrmSchedule.Label41.Caption = FrmWeek1WAR.Label23.Caption
FrmSchedule.Label42.Caption = FrmWeek1WAR.Label37.Caption
FrmSchedule.Label43.Caption = FrmWeek1WAR.Label26.Caption
FrmSchedule.Label44.Caption = FrmWeek1WAR.Label27.Caption
FrmSchedule.Label45.Caption = FrmWeek1WAR.Label28.Caption
FrmSchedule.Label46.Caption = FrmWeek1WAR.Label29.Caption
FrmSchedule.Label47.Caption = FrmWeek1WAR.Label30.Caption
FrmSchedule.Label48.Caption = FrmWeek1WAR.Label38.Caption
Dim conConnection As ADODB.Connection
Dim rs As ADODB.Recordset
Dim sqlStr As String
Dim clone_rs As ADODB.Recordset
Set conConnection = New ADODB.Connection
Set rs = New ADODB.Recordset
With conConnection
.ConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & _
App.Path & "\" & "WAP.mdb;Mode=Read|Write"
.Open
End With
With rs
.CursorLocation = adUseClient
.CursorType = adOpenStatic
.LockType = adLockBatchOptimistic
.ActiveConnection = conConnection
.Open "war", conConnection, adOpenForwardOnly
End With
'Set clone_rs = rs.Clone
With arsProjects
If rs.BOF And rs.EOF Then
.Requery
.MoveFirst
.MoveLast
Else
sqlStr = "SELECT activity_desc FROM war WHERE time = '8' and activity_date = '" & Label37.Caption & "' and sales_group = 'ALC Holdings CO., INC' and day = 'Monday'"
Text1.Text = rs.Fields("activity_desc")
sqlStr = "SELECT activity_desc FROM war WHERE time = '9' and activity_date = '" & Label38.Caption & "' and sales_group = 'ALC Holdings CO., INC' and day = 'Tuesday'"
Text2.Text = rs.Fields("activity_desc")
End If
End With
Set rs = Nothing
Set conConnection = Nothing
End Sub
If I'm doing it wrong, what would be the proper function or code for me to achieve what I wanted. Any help and suggestions would be much appreciated. By The way, I am trying to use multiple select query to achieve this.
Your assigning the SELECT statement to sqlStr but it doesn't look like your using sqlStr anywhere. In rs.Open you have a select statement of "war" and not sqlStr.