Type mismatch for Currency variable/data field in VBA (Access) - vba

I'm creating a small application in Microsoft Access using VBA. I've encountered what I suspect is a simple issue and I can't figure it out. I have this event on a button-click:
Private Sub CalculateCredit_Click()
Dim TotalCredit As Currency
TotalCredit = CurrentDb.OpenRecordset("SELECT SUM(Credit) FROM EmployeeCredit")
End Sub
The EmployeeCredit.Credit field's data type is Currency; my TotalCredit variable is of type Currency. When I click the button, I get a compile error that there is a type mismatch between EmployeeCredit.Credit and TotalCredit.
Any idea why this is happening?

You can't assign a recordset to a Currency variable.
Retrieve the first field:
TotalCredit = CurrentDb.OpenRecordset("SELECT SUM(Credit) FROM EmployeeCredit")(0).Value
Or use DSum:
TotalCredit = DSum("Credit", "EmployeeCredit")

Related

How to set value of combobox with two columns?

I am using an unbound form. I have a combobox called PO_Number, and a combobox called Vendor_Name. In an after update event for the PO_Number, I use the PO_Number and get the Vendor_Name. In VBA, I try to set the value of the combobox like so:
Vendor_Name.Value = rs!Vendor_Name
It runs but the text does not show up in the combobox.
How can I set the value of a combobox?
After Update event:
Private Sub PO_Number_AfterUpdate()
On Error GoTo ErrorHandler
Dim sql As String
Dim rs As DAO.Recordset
sql = "SELECT v.Vendor_Name, p.PO_Date, p.Description FROM PO as p INNER JOIN Vendor as v ON p.Vendor_Number = v.Vendor_Number WHERE p.PO_Number = " & PO_Number.value
Set rs = CurrentDb.OpenRecordset(sql)
If Not rs.EOF Then
rs.MoveFirst
Vendor_Name.Value = rs!Vendor_Name
PO_Date.value = rs!PO_Date
Description_Tb.value = rs!Description
End If
Exit Sub
ErrorHandler:
Err.Raise Number:=Err.Number, Description:=Err.Description
Exit Sub
End Sub
I looked through several answers, all of which were for C# or VB.Net.
EDIT:
I considered using a textbox for Vendor Name, but I need the combobox because the user needs to select a different vendor.
I also realized there are two columns to my Vendor_Name combobox. The first stores the Vendor_Number, the second stores the Vendor_Name. The bound column is set to 1 (Vendor_Name).
How can I set the value of the combobox with two columns?
I would like to set it like so:
Vendor_Name.Column(0) = rs!Vendor_Number
Vendor_Name.Column(1) = rs!Vendor_Name
but it gives me:
Run time error 424.
Object required
Source of issue is misunderstanding BoundColumn property. BoundColumn is not zero-based.
If combobox RowSource is SELECT Vendor_Number, Vendor_Name FROM Vendors; and BoundColumn is 1 then it is looking at Vendor_Number, not Vendor_Name.
Column Index is zero-based. So Column(0) refers to first column.
Need to set combobox Value property with Vendor_Number then associated Vendor_Name will display.
Use BOUND form and BOUND controls and less VBA will be need and a lot of these complications will go away.

Reference table and form text box MS Access VBA

Pardon the code below. I am a VBA novice. I am looking to upon clicking a form button, inform customers that they must make another library selection if the item they have chosen is checked out. I determine something is checked out if the "Check In Date" for the most recent date in the "1Transaction" table is NULL. Note for every check in and check out, a new record is created in the 1Transaction table and every record (whether check in or check out) will have the check out date info. So the logic, take the most recent date for the lease (book) number and if there is no return date then it is still checked out. The code below is meant to make the references and return a message box in VBA but I am stuck. I understand logically what I require but I know my VBA syntax is very off. Thanks.
Private Sub Check_Out()
If [1Transactions].[Asset].Value = Me.Lease_Num
And DMax([Tables]![1Transactions].[Check Out Date])
And [Tables]![1Transactions].[Check In Date] = NULL
Then MsgBox "The requested documents are currently checked out"
End If
DoCmd.OpenForm "Check In"
End Sub
Note:
1Transactions = Table holding all check in/out data
Me.Lease_Num = value pulled from combo box that user fills out to provide "lease number" (book code) they are interested in checking out.
Okay - instead of trying to modify every line of your code, I think it's better to use a Parameter Query to simple check if the item is out now
First create a query using your transactions table - modify the SQL to below
and save it as "qdfLease"
PARAMETERS [What Lease Num] Text ( 255 ); SELECT TOP 1
[1Transactions].Asset, [1Transactions].[Check Out Date],
[1Transactions].[Check In Date] FROM 1Transactions WHERE
([1Transactions].Asset = [What Lease Num]) And ([1Transactions].[Check
In Date] Is Null) ORDER BY [1Transactions].[Check Out Date] DESC;
Modify the code in your sub to:
Dim qdf As DAO.QueryDef
Dim rs As DAO.Recordset
Dim strLeaseNum As String
strLeaseNum = nz(Me.Lease_Num,"")
Set qdfLease = CurrentDb.QueryDefs("qdfLease")
qdfLease.Parameters("What Lease Num") = strLeaseNum
Set rs = qdfLease.OpenRecordset(dbOpenDynaset, dbReadOnly)
If rs.EOF Then
' Item is Checked In
Else
' Item is Checked Out
End If
rs.Close
Set rs = Nothing
You have [1Transactions].[Check Out Date].Value = Me.Lease_Num
Is that what you want to compare the lease_num to? It sounds like it should be a different field name in [1Transactions]
I would change this
[Tables]![1Transactions].[Check In Date] = NULL
to this
IsNull([Tables]![1Transactions].[Check In Date])
What are you trying to compare here
DMax([Tables]![1Transactions].[Check Out Date])

Declare Data type that has the word order

I'm having an issue declaring my data type because the word "order" is in the name. What I'd like to do is declare "Original Order Bulk Status" As a Boolean Data type, but I'm getting an error message saying "expected end of statement"
Any ideas on how to fix this?
I'm trying to get this data type as a page field for a pivot table so right now for the dim I have:
Dim Original Order Bulk Status As Boolean
Then:
PivotFields("Original Order Bulk Status").Orientation:=xlPageField
Basically I just need to declare the data type for this because I was getting the error saying
Run time error 1004: "Unable to get the PivotFields property of the PivotTable class"
Thanks for the help!
Variable names can't contain spaces. You could use
Dim Original_Order_Bulk_Status As Boolean
or
Dim OriginalOrderBulkStatus As Boolean

Check if ArrayList contains an object with a property that equals a specific value

So I have an application in VB.net that is pulling data from a table and inserting it into an arraylist to be used later. What I want to do is before adding the object to the arraylist, I want to check that arraylist to see if the object exists, but I want to be able to check based off a particular property of that object.
Here is an example of what I am talking about:
Lets say Im pulling info from a table with the following columns:
InvoiceNo|DateCharged|Quantity|TotalCharge
I have a SQL statement that pulls info from a table and then I use a data reader to go through the info. My Code looks somewhat like this:
Dim dbobjM As New clsDbobjManual()
If dbobjM.Exec_SQL_DR("SELECT InvoiceNo, DateCharged, Quantity, TotalCharges From Invoices") = 0 Then
If dbobjM.DataReader.HasRows Then
Dim invoicelist As New ArrayList(5000)
Dim invoiceno As String = String.Empty
Do While dbobjM.DataReader.Read()
invoicelist.Add(New Invoice(dbobjM.DataReader.GetInt32(0), dbobjM.DataReader.Value(1), dbobjM.DataReader.GetInt32(2), dbobjM.DataReader.GetFloat(3)))
Loop
End If
End if
(Exec_SQL_DR is a function in the clsDbobjManual class that check to make sure the SQL is in the proper syntax first and checks that records are returned otherwise it returns an error)
Basically what I want to do is before I add a new object to the arraylist I want to check if an object already exists in the list where the InvoiceNo is a particular value, or the value pulled from the table each time to make sure there is no duplicates. I want one object in the list for each InvoiceNo.
Im looking for something like:
If Not invoicelist.Contains(Object where InvoiceNo = dbobjM.DataReader.GetInt32(0)) Then
invoicelist.Add
End If
But I cant seem to find what I need, any help is greatly appreciated
There is no need to use the outdated ArrayList: a List will serve you better. Please see ArrayList vs List<> in C# if you need reasons - the advantages for a list apply to VB.NET too.
Without seeing your clsDbobjManual or Invoice classes, I ended up writing the minimal code to do what you're after, which is basically the check for invoices.Any(Function(i) i.InvoiceNo = inv.InvoiceNo), which you can do if you have the data in a List(Of Invoice).
Please note that I assumed that the appropriate data types have been used in the database - you should use the Decimal type for money as otherwise you can end up with significant rounding errors, and a date should be stored as DateTime, not as a string.
Imports System.Data.SqlClient
Module Module1
Class Invoice
Property InvoiceNo As Integer
Property DateCharged As DateTime
Property Quantity As Integer
Property TotalCharges As Decimal
Sub New()
' empty constructor
End Sub
Sub New(invoiceNo As Integer, dateCharged As DateTime, quantity As Integer, totalCharges As Decimal)
Me.InvoiceNo = invoiceNo
Me.DateCharged = dateCharged
Me.Quantity = quantity
Me.TotalCharges = totalCharges
End Sub
End Class
Function LoadData() As List(Of Invoice)
Dim invoices As New List(Of Invoice)
Dim connStr As String = "your connection string"
Dim sql = "SELECT InvoiceNo, DateCharged, Quantity, TotalCharges From Invoices"
Using sqlConn As New SqlConnection(connStr)
Using sqlCmd As New SqlCommand(sql, sqlConn)
Dim reader As SqlDataReader = sqlCmd.ExecuteReader()
While reader.Read()
Dim inv As New Invoice(reader.GetInt32(0), reader.GetDateTime(1), reader.GetInt32(2), reader.GetDecimal(3))
If Not (invoices.Any(Function(i) i.InvoiceNo = inv.InvoiceNo)) Then
invoices.Add(inv)
Else
' there is a duplicate invoice number
End If
End While
End Using
End Using
Return invoices
End Function
Sub Main()
Dim uniqueInvoices As List(Of Invoice) = LoadData()
' uniqueInvoices now contains the data
End Sub
End Module
If you had a lot of invoice entries to go through, you would likely be better off writing an SQL query to do that.
If you actually just want to find duplicate invoice numbers, you could use the SQL
SELECT [InvoiceNo]
FROM testTable
GROUP BY [InvoiceNo]
HAVING COUNT([InvoiceNo]) > 1
Finally, please ensure that you are using Option Strict On so that you don't make accidental data type errors - they can drastically slow down your program and lead to erroneous results.
You can use linq to select the objects that matches your condition.
Dim result = (From invoiceitem As Invoice
In invoicelist
Where invoiceitem.InvoiceNo = dbobjM.DataReader.GetInt32(0)
Select invoiceitem).ToList()
If Not result.Count > 0 Then
invoicelist.Add(New Invoice(dbobjM.DataReader.GetInt32(0), dbobjM.DataReader.Value(1), dbobjM.DataReader.GetInt32(2), dbobjM.DataReader.GetFloat(3)))
End If

Error: Conversion from type DBNull to type string is not valid

again i came for a problem. Please help me to do this. I was tried to get quantity from db make use of the selection in list box. I got answered with listbox1. If i selected the item in listbox1 the quantity would appear in textbox1. But in this same code will not work for listbox2 with textbox4.. Here i given the code...
$Con.open()
$Dim cd as new oledb.oledbcommand("Select Quantity from tlist where tool_name"& "'"listbox2.selecteditem & "'" & "", con)
$dim rs as oledb.oledbdatareader
$do while rs.read
$textbox4.text=(rs("Quantity))
$loop
$con.close
Here i got the error as "Conversion from type DBNull to type string is not valid" Plz let me know what will i do.??
There are a few issues.
Your query is a bit off. It currently reads Select Quantity from tlist where tool_name'valueOfListbox2'". It should probably read Select Quantity from tlist where tool_name = 'valueOfListbox2'.
Your getting a null value back and are not checking for a null return before writing the value out, hence the error. You can use the following IF statement to verify your value is not null:
If NOT IsDbNull(rs("Quantity")) Then
Also, you're missing a double quote around "Quantity".