I am using SQL in vb.net. I believe I have successfully connected to the database and at the moment I am able to display the information I have received in a message box with:
sql = "SELECT ID FROM LoginInformation WHERE Username = '" & txt_Username.Text & "' AND Password = '" & txt_Password.Text & "'"
DataSets = database.sqlSelect(sql)
MsgBox(DataSets.Tables("LoginInformation").Rows(0).Item(0))
However, I do not want it to show the same cell of the database every time I use this code and I am unsure as to how to display what I am actually looking for with the SQL statement. From the above code, I have tried to find the 'ID' but it will always display the cell located at (0,0)
Any help will be appreciated!
Thanks.
You should loop throw this DataSets.Tables("LoginInformation") to get all the rows and columns.
See this example quoted from here:
Private Sub PrintRows(ByVal dataSet As DataSet)
Dim table As DataTable
Dim row As DataRow
Dim column As DataColumn
For Each table in dataSet.Tables
For Each row In table.Rows
For Each column in table.Columns
Console.WriteLine(row(column))
Next column
Next row
Next table
End Sub
Related
I am fairly new to SQL and VBA. I want to create a function and then make it an add-in, where I will be able to select a range of ids and a range of column names and retrieve the data from an excel file (ADODB.Connection).
I have found some instructions here (https://excel-macro.tutorialhorizon.com/vba-excel-read-excel-workbook-as-database-using-odbc-source/?fbclid=IwAR3uaiUOCwDVNhM_gMbsPdHWFPodxL0EsIcTAeRh6Qu1GzLRjB4eW8QR9is); I have replicated and adjusted the code for my case. But I can't find a way to:
make it a public function.
adjust the SQL query for selecting the selected through the function ids (rows) and column names.
the code so far:
Public Function getData(id As Range, cols As Range)
Set ActiveC = Application.ActiveCell
Set Connection = CreateObject("ADODB.Connection")
Connection.Open "DSN=SumitODBC"
strQuery = "SELECT " & cols & " FROM [Sheet1$A1:Z500] where id = '" & id & "' "
Set resultSet = Connection.Execute(strQuery)
Do While Not resultSet.EOF
ActiveC.Value = resultSet.Fields("cols").Value
resultSet.movenext
Loop
resultSet.Close
End Function
A simplistic dataset:
Data and what I want to achive
at work, we're trying to build a database to get an output of all kinds of data from different excel tables (items in stock, sales per week, price, etc) into one table by using the ItemID as primary key for all the tables and as a user input for the queries.
My goal is to let the user enter multiple itemIDs seperated by commas and get back a table with multiple rows (one for each item).
I have now created a form with all the fields I need and have used one of my queries that I implemented before as my data source.
I'm trying to write some code for my On-Start event and have used an example someone posted online regarding entering multiple parameters:
Option Compare Database
Const record source = Query01
Private Sub Form_Open(Cancel As Integer)
Dim m As String
m = InputBox("Enter itemID (numeric), separated by comma", "itemID")
If m <> "" Then
Me.RecordSource = record_source & " where itemID in (" & m & ");"
Else
Me.RecordSource = record_source
End If
End Sub
For the line:
Me.RecordSource = record_source & " where SKU in (" & m & ");"
I get the error
Run-Time error '2580'
The record source 'where SKU in (" & m & ");' specified on this form or report does not exist.
Do I need to declare my record source differently in the second line? Do I need to somehow specify which table I get my "itemID" field out of? The Query01 that I put as my data source gets fields out of three different tables.
Thank you so much for your help!
Cheers!
I fixed my issue by using the Filter-method instead and just deleting the declaration in line 2 since the data source was already defined in the properties sheet before.
My VBA code:
Private Sub Form_Open(Cancel As Integer)
Dim m As String
m = InputBox("Enter itemID (numeric), separated by comma", "itemID")
If m <> "" Then
Me.Filter = "itemID in (" & m & ")"
Me.FilterOn = True
Else
Me.FilterOn = False
End If
End Sub
Hope this helps anyone encountering a similar problem.
Cheers!
I have a code which takes data from a DB with a SQL statement with 2 WHERE conditions. What I want is to paste the recordset into sheet2 . Each recordset has 13 columns of data. Problem is, when I take the recordset and I paste them into sheet2, the pasted columns are only the first 3.To note that from column 4 to 10 there can be empty columns
Do you know what could be the problem?
UPDATE 3: Updated question and code according to feedback
'Create the SQL statement to retrieve the data from table.
With Recordset
SQL = "SELECT * FROM Data WHERE [PRini] = '" & var & "' or [QAini] = '" & var & "' "
'Create the ADODB recordset object.
Set rs = New ADODB.Recordset 'assign memory to the recordset
'ConnectionString Open '—-5 aguments—-
'Source, ActiveConnection, CursorType, LockType, Options
rs.Open SQL, cnn
'If not, write the recordset values in the sheet.
Sheet2.Range("A2").CopyFromRecordset rs 'PROBLEM: The pasted row is not the full one in access, but only the first 3 columns. from the 4th to the 10th there are no data, from 11th to 13th there are but are not taken
It's hard to know exactly the problem, and there are all sorts of things wrong with this code. The issues which may be related to your problem include:
SQL = "SELECT * FROM Data WHERE [PRini] or [QAini] = '" & var & "' " will return rows where either PRini is TRUE or QAini = var. Did you mean SQL = "SELECT * FROM Data WHERE [PRini] = '" & var & "' or [QAini] = '" & var & "' " - i.e. where PRini = var or QAini = var?
the autofilter is applied to the table "Table1", but there is nothing to say this table has the same dimensions as the recordset in either direction (copyFromRecordset does not create or populate a table, it just pastes the values straight in to the worksheet). If you need the data in a table, use the QueryTable.Connection, QueryTable.CommandType and QueryTable.CommandText properties to connect the table to the SQL server directly (see the MSDN docs). Or apply the autofilter to the range containing the data (Sheet2.Range("A2").CurrentRegion will do).
there is nothing in the code that references the current date. The code from 'Filter for the date onwards just copies the visible cells from the first two columns into a listBox control.
Why not include the date condition in the SQL? That would be the approach I would use (e.g. SELECT * FROM Data WHERE ([PRini] = 'something' OR [QAini] = 'something') AND [MyDateColumn] < DATE();)
I have to create a text box in MS Access where users are able to see the top 3 records of a particular result set. So even if the query results in 5 records I only want it to display the top 3 records as three textboxes (sometimes the result may also be 1,2 or 0 records).
I took the easy way out and created a new subform which was connected to the parent form using master/child field. The textbox was placed in the details part of the subform and as a recordsource of the subfrom used the following query:
Select top 3 tbl1.column1, tbl1.column2
from tbl1
column1 is the control source for the textbox and column2 is the column I have used for master/child link.
Now the catch is that the query works fine when I use it without top 3. But when I use top 3 the textbox suddenly disappears and the subform is completely blank.
I am not able to identify the cause of the error. My guess is that it has something to do with type of the subform. Not sure.
Is there any other way I can have a text box whose number can vary on the basis of the results?(but limiting the resultset to 3)
Appreciate the help.
Textbox are not meant to hold more than 1 value.
You are trying to assign three results of 2 columns to one textbox(No can do).
Use listbox to populate as you are doing, assigning the query you just wrote in the rowsource of the list(no subforms needed). This way users will see the three records.
You could use a textbox in order to accomplish what you are trying to do. But will require some VBA coding to accomplish this.
Public function CombineValuesForTextBox() as string
Dim rst as dao.recordset
Dim strSQL as string
strSQL = "SELECT TOP 3 tbl1.Column1 as field1, tbl1.Column2 as field2 " & _
"FROM tbl1;"
set rst = currentdb.openrecordset(strsql)
if rst.recordcount = 0 then 'Checks if the recordset has records or not
CombineValuesForTextBox = "No records found"
goto EndCode 'Or replace with what actions to take if no records are found
else
rst.movelast 'Forces the recordset to fully load
rst.movefirst
do while not rst.eof
if CombineValuesForTextBox = "" or CombineValuesForTextBox = empty then
CombineValuesForTextBox = rst![field1] & " - " & rst![Field2]
else
CombineValuesForTextBox = CombineValuesForTextBox & vbcrlf & _
rst![field1] & " - " & rst![Field2]
end if
Loop
end if
rst.close
set rst = nothing
EndCode:
if not rst is nothing then
rst.close
set rst = nothing
end if
end function
Then on your form put in the code (be sure the textbox is unbound...)
me.textbox = CombineValuesForTextBox
This kind of hard to explain specially since english is not my first language, let's see if can make myself understand, im trying to perform a Select query to get the records within a time frame(column ContactDate contains the date/time values) the query is as follow:
SELECT Val([ACD_ID] & Format(DateValue([ContactDate]),'0')) AS SEARCH_CODE, CFinal, 1 AS Expr1,
COPCFCR, FCRPossible, RecordName
FROM [YTD-Daily_Report]
WHERE ((([YTD-Daily_Report].[ContactDate])>=#9/01/2014#
And ([YTD-Daily_Report].[ContactDate])<=#10/01/2014#));
In the source Table(YTD-Daily_Report) COPCFCR and FCRPossible are define as Checkboxes(true or false), when i run this query using Access within the database it all works well i get a column with the concatenated value of the ID + Date, a column containing the score, a column with a 1 in it, a column with the COPCFCR value(true or false), a column with the FCRPossible value(true or false), and column with the RecordName, at this point if i compared with the values on the table they match 100%.
Now, i took this query and put it on an Excel workbook but when it runs it returns the values for the columns COPCFCR and FCRPossible wrong, sometimes a false is returned as true or viceversa and other times the values match 100% with the corresponding values on the source table, for example in some rows COPCFCR is returned as true when it should be false according to the source table.
Here is the Excel VBA code I'm using:
Dim rsSource As New Recordset
Dim m_Connection As New Connection
Dim rngTarget as range
dim result as long
m_Connection.Provider = "Microsoft.ACE.OLEDB.12.0"
m_Connection.Open "Path and name of the Database"
strQuery = "SELECT Val([ACD_ID] & Format(DateValue([ContactDate]),'0')) AS SEARCH_CODE, CFinal, 1 AS Expr1, COPCFCR, FCRPossible, RecordName" & Chr(13) & _
"FROM [YTD-Daily_Report]" & Chr(13) & _
"WHERE ((([YTD-Daily_Report].[ContactDate])>=#" & Format(START_DATE, "m/dd/yyyy") & "# And ([YTD-Daily_Report].[ContactDate])<=#" & Format(STOP_DATE + 1, "m/dd/yyyy") & "#));"
rsSource.Open strQuery, m_Connection, adOpenForwardOnly, adLockReadOnly
Set rngTarget = Range("A2")
result = rngTarget.CopyFromRecordset(rsSource)
If rsSource.State Then rsSource.Close
Set rsSource = Nothing
If m_Connection.State Then m_Connection.Close
Set m_Connection = Nothing
Any ideas what could be happening?
It seems the database file was corrupted and this caused the data to be exported in a different way that it was call for. The query is working fine as it is.