Unable to add records more than 28 in access database - vb.net

I am making my first project using vb.net and access. I am trying to develop a project in which the data of patients of the is added from different counters.it works fine till 22nd or 23rd record entered. after that adding new record over writes the last saved record.
to check the database i deleted some record (say after deletion there are 13 records left in the database) and tried to add new record, it gives the same problem, the 13th record is overwritten by the new record.
i deleted all the records and tried to add new record, the first record successfully entered but after that new record entry over writes the last (only) record.
i'm unable to understand the problem
code for saving data is
Private Sub Save()
'Dim st As String
Dim str As String
btnSave_Click = False
str = check
If Not str = "" Then
MsgBox(str, vbInformation, "Patient Registration")
btnSave_Click = False
Exit Sub
End If
If conn.State = 0 Then
Module1.openConnection()
End If
If Not rsDept Is Nothing Then
If rsDept.State = 0 Then
Call openRecordset("SELECT * FROM tblDept", rsDept)
End If
Else
Call openRecordset("SELECT * FROM tblDept", rsDept)
End If
If Not rsData Is Nothing Then
If rsData.State = 0 Then
Call openRecordset("Select * from tblPatientRecord", rsData)
End If
Else
Call openRecordset("Select * from tblPatientRecord", rsData)
End If
conn.BeginTrans()
On Error GoTo ProcError
If Not (rsData.BOF And rsData.EOF) Then
rsData.MoveLast()
Call addData(rsData)
Else
Call addData(rsData)
End If
conn.CommitTrans()
MsgBox("Patient's Record Saved Successfully...!", MsgBoxStyle.Information, "Patient Registration")
Call loadDataListview()
Call fieldDisable()
Call Disable_SearchButtons()
btnSave_Click = True
comDepart.Enabled = False
conn.Close()
ProcError:
If Err.Number <> 0 Then
conn.RollbackTrans()
MsgBox(Err.Number & " " & Err.Description)
Call addNewR()
Exit Sub
End If
End Sub
Private Sub addData(rData As ADODB.Recordset)
Dim rsPaymentType As New ADODB.Recordset
'Dim str As String
If Not (rData.BOF And rsData.EOF) Then
rData.MoveFirst()
If rData.RecordCount > 0 Then
Do
If txthn.Text = rData("hNumber").Value Then
Call addVisit()
conn.Execute("update tblPatientRecord set visitNo = '" & vNo.Text & "' where hNumber = '" & txthn.Text & "'")
Call fieldEnable()
Exit Sub
End If
rData.MoveNext()
Loop Until rData.EOF
End If
End If
rData.AddNew()
rData("hNumber").Value = txthn.Text
rData("fName").Value = txtfn.Text
rData("contactNo").Value = txtContact.Text
rData("address").Value = txtaddress.Text
rData("cnic").Value = txtcnic.Text
'rData("cnic").Value = rCNIC()
rsData("visitNo").Value = vNo.Text
rsData("cnicSD").Value = comSD.Text
''Add gender as selected
If radmale.Checked = True Then
rData("gender").Value = radmale.Text
ElseIf radfemale.Checked = True Then
rData("gender").Value = radfemale.Text
Else
rData("gender").Value = " - "
End If
If txtAge.Text < 105 Or Year(dtAgePicker.Value) < 1915 Then
Call addAge()
'MsgBox("data of tblAge added")
Else
MsgBox("Please Enter Correct Age ", vbCritical, "")
txtAge.Select()
Exit Sub
End If
If comRelation.Text = "Select Relation with Patient" Or comRelation.Text = "" Then
comRelation.Text = "Not Selected"
End If
If txtfh.Text = "" Then
txtfh.Text = "Not Given"
End If
Call addRelation()
'Save Department ID as selected
If comDepart.Text <> "Select Department" Then
Call addVisit()
'MsgBox("data of tblVisit added")
Else
MsgBox("Please Enter the Department ", vbCritical, "")
comDepart.Select()
Exit Sub
End If
If Not rsPaymentType Is Nothing Then
If rsPaymentType.State = 0 Then
Call openRecordset("Select * from tblPaymentType", rsPaymentType)
'MsgBox("Patient record is open" & rsData.State)
End If
Else
Call openRecordset("Select * from tblPaymentType", rsPaymentType)
'MsgBox("Patient record is open")
End If
If Not (rsPaymentType.BOF And rsPaymentType.EOF) Then
rsPaymentType.MoveFirst()
Do
If rsPaymentType("paymentType").Value = comPaymentType.Text Then
rData("paymentType").Value = rsPaymentType("paymentTypeID").Value
Exit Do
Else
rData("paymentType").Value = 0
End If
rsPaymentType.MoveNext()
Loop Until rsPaymentType.EOF
End If
rsData.Update()
End Sub
Public Function h_N0_Generator(rs As ADODB.Recordset) As String
Dim str, p1() As String
Dim auto_long As Long
Dim hMonth As String
Dim strCounter As String, temp As String
'this counter file is added to make the hNumber unique for multiple counter /* in the file counter number is added and have respective counter number only*/
FileOpen(FileNum, "C048ounter.txt", OpenMode.Input)
strCounter = LineInput(FileNum)
FileClose(FileNum)
If strCounter = "" Then
strCounter = "1"
End If
hMonth = Month(Now).ToString("D2")
If (rs.EOF And rs.BOF) Then
h_N0_Generator = "NIRM-" & Year(Now) & "-" & hMonth & "-" & "00000" & strCounter
Else
rs.MoveLast()
str = rs("HNumber").Value
p1 = str.Split("-")
' check if the current month is the same as in last stored Hospital No or not
'if yes the last five digits increment otherwise it restarts with 0
If p1(2) = Month(Now) And p1(1) = Year(Now) Then
temp = Right(rs(0).Value, 6)
auto_long = Left(temp, 5) + 1
h_N0_Generator = "NIRM-" & Year(Now) & "-" & hMonth & "-" & Right("00000" & auto_long, 5) & strCounter
Else
h_N0_Generator = "NIRM-" & Year(Now) & "-" & hMonth & "-" & "00000" & strCounter
End If
End If
'Return auto_num
End Function

Related

Visual Basic- I've got an error

It says error on Line 32....
The given code is of visual basic. I guess I have got everything correct but have no clue what I did wrong. when I checked about it in the console it said line 32
Module Module1
Sub Main()
Dim isInKG As Boolean = Nothing
Dim canDrink As Boolean = Nothing
Dim isSeniorCitizen As Boolean = Nothing
Console.WriteLine("what is your age?")
Dim age As Integer = Console.ReadLine()
Dim outcomeKG As String = Nothing
Dim outcomeSenior As String = Nothing
Dim outcomeDrink As String = Nothing
If age <> 5 Then
isInKG = False
outcomeKG = "You arent in KG"
Else
isInKG = True
outcomeKG = "You are in KG"
End If
If age >= 65 Then
isSeniorCitizen = True
outcomeSenior = "You are a Senior Citizen"
Else
isSeniorCitizen = False
outcomeSenior = "You are a Junior Citizen"
End If
If age >= 21 Then
canDrink = True
outcomeDrink = "Go and get drunk"
Else
canDrink = False
outcomeDrink = "Sorry Kiddo Not until 21 "
End If
Console.WriteLine(outcomeDrink & " " & outcomeKG & " " & outcomeSenior " " &)
Console.ReadLine()
End Sub
End Module
Third row from the bottom has wrong order...
try this
Console.WriteLine(outcomeDrink & " " & outcomeKG & " " & outcomeSenior & " ")

Access VBA Filter RecordCount not properly updating value

I have a form that I have built a filter search on that runs "after_update". When the filter results in no records the form fails and shows blank. To get around this i found several posts recommending to add a "RecordCount" and use an "if" statement to then trigger the filter if it is not <1 or =0. My issue is that the value of the RecordCount seems to be showing the # of records from the last ran filter selections, not the current filter. I have tried several methods to "requery" and update the value of the RecordCount after the filter is applied but I cant get it to update as i intend it to work.
Example:
Filter 1: Results in 14 records, the debug.print recordcount displays 1
Filter 2: Results in 22 records, the debug.print recordcount displays 14
Filter 3: Results in 0 records, Form fails, the debug.print recordcount displays 22
Code:
Private Sub ApplyFilterBtn_Click()
On Error GoTo Err_ApplyFilterBtn_Click
Dim stFilter As String
stFilter = ""
If Nz(Me.FilterOwner, "") <> "" Then
stFilter = stFilter & "[MachineOwner] = " & Me.FilterOwner & " AND "
End If
If Nz(Me.FilterType, "") <> "" Then
stFilter = stFilter & "[MachineType] = " & Me.FilterType & " AND "
End If
If Nz(Me.FilterSubType, "") <> "" Then
stFilter = stFilter & "[MachineSubType] = " & Me.FilterSubType & " AND "
End If
If Nz(Me.FilterMake, "") <> "" Then
stFilter = stFilter & "[Make] Like '" & Me.FilterMake & "' AND "
End If
If Nz(Me.FilterModel, "") <> "" Then
stFilter = stFilter & "[Model] Like '*" & Me.FilterModel & "*' AND "
End If
If Nz(Me.FilterSN, "") <> "" Then
stFilter = stFilter & "[SN] Like '" & Me.FilterSN & "' AND "
End If
If Nz(Me.FilterStatus, "") <> "" Then
stFilter = stFilter & "[NewStatus] = " & Me.FilterStatus & " AND "
End If
If stFilter <> "" Then
stFilter = Left(stFilter, Len(stFilter) - 5) 'Remove the extra AND
'<<<<<<<Issue starts here<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
Me.Recordset.Clone
Me.RecordsetClone.Filter = stFilter
Me.RecordsetClone.MoveLast
' Me.RecordsetClone.MoveNext 'Tried this - did not help
' Me.RecordsetClone.Requery 'tried this - did not help
' Me.Filter = stFilter ' Tries this - did not help
'debugging to see value of RecordCount
Debug.Print stFilter
Debug.Print Me.RecordsetClone.RecordCount
'>>>>>> Recordsetclone.RecordCount value not refreshing properly above, shows previously called filter record count
If Me.RecordsetClone.RecordCount < 1 Then ' no records, don't filter
'If Not (Me.RecordsetClone.BOF And Me.RecordsetClone.EOF) Then 'work around attempt 2 - failed
'If Me.NoMatch Then 'Work around Attempt 3 - failed
RemoveFilterBtn_Click ' Call sub that Clears filter
MsgBox "Filter Results in No records", vbOKOnly, "No Results"
Else ' there are records, turn on filter
Me.Filter = stFilter
Me.FilterOn = True
End If 'Me.RecordCount < 1
Else
Me.FilterOn = False
RemoveFilterBtn_Click ' Clears filter
End If 'stFilter <> ""
Exit_ApplyFilterBtn_Click:
Exit Sub
Err_ApplyFilterBtn_Click:
MsgBox Err.Description
Resume Exit_ApplyFilterBtn_Click
End Sub
Private Sub RemoveFilterBtn_Click()
On Error GoTo Err_RemoveFilterBtn_Click
'Sets Filter Field Values to Blank
Me.FilterOwner = ""
Me.FilterType = ""
Me.FilterMake = ""
Me.FilterModel = ""
Me.FilterSN = ""
Me.FilterStatus = ""
Me.FilterSubType = ""
'Removes Filter
Me.Filter = ""
Me.FilterOn = False
Exit_RemoveFilterBtn_Click:
Exit Sub
Err_RemoveFilterBtn_Click:
MsgBox Err.Description
Resume Exit_RemoveFilterBtn_Click
End Sub
It is simpler but you need the right syntax:
Dim rst As DAO.Recordset
Dim rstFiltered As DAO.Recordset
Set rst = Me.RecordsetClone
rst.Filter = stFilter
Set rstFiltered = rst.OpenRecordset()
If rstFiltered.RecordCount > 0 Then
' Do stuff.
End If
rstFiltered.Close
Set rstFiltered = Nothing
Set rst = Nothing

VBA: Error 3265 - "Item not found in this collection"

In Access 2016 I'm trying to open a recordset and save data from it in other variables, but I keep getting this error.
The program itself has more parts, but I only get error in this one, it just update data on its database.
This is my code:
Option Compare Database
Option Explicit
Private Sub btnValidateTimesheet_Click()
' Update timesheet to "Justificat"
Dim intIdTimesheet As Integer
If IsNull(cmbDraftTimesheets.Value) Then
MsgBox("You have to select a timesheet that is Borrador")
Exit Sub
End If
intIdTimesheet = cmbDraftTimesheets.Column(0)
DoCmd.SetWarnings False
DoCmd.RunSQL "update Timesheets set estat = ""Justificat"" where id=" & intIdTimesheet
DoCmd.SetWarnings True
End Sub
Private Sub btnValidateTimesheetLines_Click()
' We select the timesheet_lines for employee, project, activity and dates selected
' For each justification, a new "Justificat" Timesheet is generated which hang timesheet_lines
' ------------------------------- Variables -------------------------------
Dim dictTsLines As Object
Set dictTsLines = CreateObject("Scripting.Dictionary")
' Form inputs
Dim intCodTreb As Integer
Dim strCodProj As String
Dim dateInici, dateFi As Date
Dim intExercici As Integer
' Query strings
Dim strSQLFrom, strSQLWhere As String
Dim strSQLCount, strSQLJustAct, strSQLTsLines As String
' Recordsets
Dim rsCount, rsJustAct, rsTimesheets, rsTsLines As Recordset
' Aux and others...
Dim continue As Integer
Dim intIdJustificacio, intIdTs As Integer
Dim strActivitat As String
' --------------------------------------- Main ---------------------------------------------
' Taking form data
intCodTreb = cmbTreballador.Column(0)
strCodProj = cmbProjecte.Column(1)
dateInici = txtDataInici.Value
dateFi = txtDataFi.Value
' We check the dates are correct
If IsNull(dateInici) Or IsNull(dateFi) Then
MsgBox("Dates can't be null")
Exit Sub
End If
If dateFi < dateInici Then
MsgBox("Start date must be earlier or the same as final date")
Exit Sub
End If
If year(dateInici) <> year(dateFi) Then
MsgBox("Dates must be in the same year")
Exit Sub
End If
intExercici = year(dateInici)
' Make of the clause FROM and WHERE of the select query of timesheet_lines
strSQLFrom = " from (timesheet_lines tsl " & _
" left join timesheets ts on tsl.timesheet_id = ts.id) " & _
" left join justificacions j on j.id = ts.id_justificacio "
strSQLWhere = " where ts.estat = ""Borrador"" " & _
" and tsl.data >= #" & Format(dateInici, "yyyy/mm/dd") & "# " & _
" and tsl.data <= #" & Format(dateFi, "yyyy/mm/dd") & "# "
If Not IsNull(intCodTreb) Then
strSQLWhere = strSQLWhere & " and tsl.cod_treb = " & intCodTreb
End If
If Not IsNull(strCodProj) Then
strSQLWhere = strSQLWhere & " and j.cod_proj=""" & strCodProj & """ "
End If
' Alert how much timesheet_lines are going to be validated
strSQLCount = "select count(*) " & strSQLFrom & strSQLWhere
Set rsCount = CurrentDb.OpenRecordset(strSQLCount)
Continue Do = MsgBox( rsCount(0) & " registries are going to be validated" & vbNewLine & _
"Do you want to continue?", vbOKCancel)
If continue <> 1 Then
Exit Sub
End If
' We select the tuples Justificacio, Activitat of timesheet_lines selected
strSQLJustAct = "select distinct ts.id_justificacio " & strSQLFrom & strSQLWhere
Set rsJustAct = CurrentDb.OpenRecordset(strSQLJustAct)
Set rsTimesheets = CurrentDb.OpenRecordset("Timesheets")
' A new timesheet is generated for each tupla
Do While Not rsJustAct.EOF
intIdJustificacio = rsJustAct(0)
strActivitat = rsJustAct(1)
rsTimesheets.AddNew
rsTimesheets!data_generacio = Now()
rsTimesheets!estat = "Justificat"
rsTimesheets!Id_justificacio = intIdJustificacio
rsTimesheets!activitat = strActivitat
rsTimesheets!data_inici = dateInici
rsTimesheets!data_fi = dateFi
rsTimesheets!exercici = intExercici
intIdTs = rsTimesheets!Id
rsTimesheets.Update
' We save the related id of the selected timesheet in a dictionary
dictTsLines.Add intIdJustificacio & "_" & strActivitat, intIdTs
rsJustAct.MoveNext
Loop
' We select all the affected timesheet_lines and we update the related timesheet using the dictionary
strSQLTsLines = "select tsl.id, tsl.timesheet_id, ts.id_justificacio, ts.activitat " & strSQLFrom & strSQLWhere
Set rsTsLines = CurrentDb.OpenRecordset(strSQLTsLines)
With rsTsLines
Do While Not .EOF
.EDIT
intIdJustificacio = !Id_justificacio
strActivitat = !activitat
!timesheet_id = dictTsLines.Item(intIdJustificacio & "_" & strActivitat)
.Update
.MoveNext
Loop
End With
rsTimesheets.Close
Set rsCount = Nothing
Set rsJustAct = Nothing
Set rsTimesheets = Nothing
Set rsTsLines = Nothing
End Sub
Debugger: The error is coming up at the line:
strActivitat = rsJustAct(1)
I checked that the data the recordset is saving exists and it does.
Your recordset contains just one column ("select distinct ts.id_justificacio"), but you are trying to read second column strActivitat = rsJustAct(1)
Add requred column to recordset.

How to check whether a string value is present in a DataGridView

Im working on a code that has a TextBox, A Button and a Datagrid view.
I want to Display "Data Not Exist" when a value in TextBox is not present on the DataGridView when i press the button.
This is my code so far
If DataGridView1.Rows.Contains(TextBox1.Text) = False Then
MessageBox.Show("Data Not Exist!")
End If
You need to loop through all rows and columns
Dim isFound As Boolean = False
For Each row As GridViewRow In DataGridView1.Rows
for i As Integer = 0 to DataGridView1.Columns.Count -1
If row.Cells[i].Text = TextBox1.text Then
isFound = True
exit for
End If
Next
Next
If (isFound) Then
MessageBox.Show("Data Exists!")
Else
MessageBox.Show("Data Not Exists!")
EndIf
You can do it easily with either using a LINQ or a ForLoop
This code will search all matches it will find across the DataGridView and will prompt in which Row and Column it sees the match.
With a ForLoop, you need to run a loop for Column and for the Row.
Private Sub SearchUsingForLoop()
Dim resultString As String = Nothing
For x = 0 To DataGridView1.ColumnCount - 1
For y = 0 To DataGridView1.RowCount - 1
If DataGridView1.Item(x, y).Value.ToString.ToUpper = txtSearch.Text.ToUpper Then
resultString &= " - Column " & x + 1 & " Row " & y + 1 & vbCrLf
End If
Next
Next
If resultString <> Nothing Then
resultString = txtSearch.Text & " found in : " & vbCrLf & resultString
Else
resultString = "Data does not exist."
End If
MsgBox(resultString)
End Sub
Do remember that index of DatagridViewRow and DatagridViewColumn starts with 0.
Another way of doing this is by LINQ:
Private Sub SearchUsingLINQ()
Dim resultSet = From dgRow As DataGridViewRow In Me.DataGridView1.Rows, _
dgCell As DataGridViewCell In dgRow.Cells _
Where dgCell.Value.ToString.ToUpper = txtSearch.Text.ToUpper _
Select dgCell
Dim resultString As String = Nothing
If resultSet.Count > 0 Then
resultString = txtSearch.Text & " found in :" & vbCrLf
For Each dgCells In resultSet
resultString &= " - Column " & dgCells.ColumnIndex + 1 & " Row " & dgCells.RowIndex + 1 & vbCrLf
Next
End If
If resultString <> Nothing Then
MsgBox(resultString)
Else
MsgBox("Data does not exist.")
End If
End Sub
Feel free to use any of those. But I suggest you to study iterating a DataGridView first.

13Type Mismatch Access 2007

I'm attempting to fix some botched up VBA from someone whom I inherited this Access database from. Aside from the hardly-useful notes left in VBA, there is no documentation, so I am trying to figure out what everything does, and if it is correct. I continue getting a 13Type Mismatch error when I am Clicking a button to add either units or a value to a table of Contributions. I thought it was an easy fix such as a messed up variable declaration, however I've changed them to Double and it didn't seem to correct my error. Does anyone see anything off the bat that they might recognize as throwing this error? Thanks ahead of time for your efforts.
Private Sub AddContributionBtn_Click()
On Error GoTo Err_AddContributionBtn
Dim Cancel As Integer
Dim CurrentNAVDate As Date
Dim CurrentNAV As Double
Dim ConfirmAddCont As Double
Dim CalcContUnits As Double
Dim CalcContValue As Double
Dim StringSQL As String
'get current NAV
CurrentNAVDate = Format(DateAdd("s", -1, DateAdd("q", DateDiff("q", "1/1/1900", Date), "1/1/1900")), "Short Date")
CurrentNAV = Format(DLookup("NetAssetValue", "NAV_Tbl", "Format(NAV_Date, ""mmddyyyy"") = " & Format(CurrentNAVDate, "mmddyyyy")), "Currency")
'validation to require either contribution units or value is entered, not both
If IsNull(Me.ContValueTxt) = True And IsNull(Me.ContUnitsTxt) = True Then
MsgBox "Please enter contribution units or value."
Me.ContUnitsTxt.SetFocus
Cancel = True
Exit Sub
ElseIf IsNull(Me.ContValueTxt) = False And IsNull(Me.ContUnitsTxt) = False Then
MsgBox "Both contribution units and value may not be entered."
Me.ContUnitsTxt.SetFocus
Cancel = True
Exit Sub
Else:
If IsNull(Me.ContValueTxt) = True And IsNull(Me.ContUnitsTxt) = False Then
'calculate contribution value from units
CalcContUnits = Me.ContUnitsTxt
CalcContValue = CalcContUnits * CurrentNAV
GoTo ConfirmAppend
ElseIf IsNull(Me.ContValueTxt) = False And IsNull(Me.ContUnitsTxt) = True Then
'calculate contribution units from value
CalcContValue = Me.ContValueTxt
CalcContUnits = CalcContValue / CurrentNAV
GoTo ConfirmAppend
End If
End If
ConfirmAppend:
'confirm contribution value and units, run append query
ConfirmAddCont = MsgBox("Add " & Format(CalcContUnits, "fixed") & " units for a contribution value of " & Format(CalcContValue, "currency") & "?", _
vbOKCancel, "Add Contribution")
If ConfirmAddCont = vbOK Then
DoCmd.Hourglass True
DoCmd.SetWarnings False
StringSQL = "INSERT INTO ContributionTbl(ContDate, ContUnits, ContNAV, ContType) VALUES (#" & Date & "#, " & CalcContUnits & ", #" & CurrentNAVDate & "#, " & 1 & ");"
DoCmd.RunSQL (StringSQL)
DoCmd.SetWarnings True
DoCmd.Hourglass False
Me.ContUnitsTxt = Null
Me.ContValueTxt = Null
Forms!PlanFrm![PlanContributedUnitsFrm].Requery
Else
Cancel = True
Exit Sub
End If
Exit_AddContributionBtn:
Exit Sub
Err_AddContributionBtn:
MsgBox Err.Number & Err.Description
Resume Exit_AddContributionBtn
End Sub
As shown in the discussion, I make our guess clearer in this temporary reponse:
Error may be here:
CurrentNAV = Format(DLookup("NetAssetValue", "NAV_Tbl", "Format(NAV_Date, ""mmddyyyy"") = " & Format(CurrentNAVDate, "mmddyyyy")), "Currency")
as DLookup("NetAssetValue",...) gets NULL,
Format(NULL, "Currency") gets 13 Type Mismatch, as I've reproduced this in Access 2007.
This can be explained:
Since there is no recent date in the table field NAV_Tbl.NetAssetValue, as in the case we get the date CurrentNAVDate = 09/30/2013 (last date of the last quarter).
So you may try code like this, by introducing varCurrency variable to handle this NULL value case:
Private Sub AddContributionBtn_Click()
On Error GoTo Err_AddContributionBtn
Dim Cancel As Integer
Dim CurrentNAVDate As Date
Dim CurrentNAV As Double
Dim ConfirmAddCont As Double
Dim CalcContUnits As Double
Dim CalcContValue As Double
Dim StringSQL As String
Dim varCurrency
'get current NAV
CurrentNAVDate = Format(DateAdd("s", -1, DateAdd("q", DateDiff("q", "1/1/1900", Date), "1/1/1900")), "Short Date")
varCurrency = DLookup("NetAssetValue", "NAV_Tbl", "Format(NAV_Date, ""mmddyyyy"") = " & Format(CurrentNAVDate, "mmddyyyy"))
If(IsNull(varCurrency) then
CurrentNAV = 0
Else
CurrentNAV = Format(varCurrency, "Currency")
End If
'validation to require either contribution units or value is entered, not both
If IsNull(Me.ContValueTxt) = True And IsNull(Me.ContUnitsTxt) = True Then
MsgBox "Please enter contribution units or value."
Me.ContUnitsTxt.SetFocus
Cancel = True
Exit Sub
ElseIf IsNull(Me.ContValueTxt) = False And IsNull(Me.ContUnitsTxt) = False Then
MsgBox "Both contribution units and value may not be entered."
Me.ContUnitsTxt.SetFocus
Cancel = True
Exit Sub
Else:
If IsNull(Me.ContValueTxt) = True And IsNull(Me.ContUnitsTxt) = False Then
'calculate contribution value from units
CalcContUnits = Me.ContUnitsTxt
CalcContValue = CalcContUnits * CurrentNAV
GoTo ConfirmAppend
ElseIf IsNull(Me.ContValueTxt) = False And IsNull(Me.ContUnitsTxt) = True Then
'calculate contribution units from value
CalcContValue = Me.ContValueTxt
CalcContUnits = CalcContValue / CurrentNAV
GoTo ConfirmAppend
End If
End If
ConfirmAppend:
'confirm contribution value and units, run append query
ConfirmAddCont = MsgBox("Add " & Format(CalcContUnits, "fixed") & " units for a contribution value of " & Format(CalcContValue, "currency") & "?", _
vbOKCancel, "Add Contribution")
If ConfirmAddCont = vbOK Then
DoCmd.Hourglass True
DoCmd.SetWarnings False
StringSQL = "INSERT INTO ContributionTbl(ContDate, ContUnits, ContNAV, ContType) VALUES (#" & Date & "#, " & CalcContUnits & ", #" & CurrentNAVDate & "#, " & 1 & ");"
DoCmd.RunSQL (StringSQL)
DoCmd.SetWarnings True
DoCmd.Hourglass False
Me.ContUnitsTxt = Null
Me.ContValueTxt = Null
Forms!PlanFrm![PlanContributedUnitsFrm].Requery
Else
Cancel = True
Exit Sub
End If
Exit_AddContributionBtn:
Exit Sub
Err_AddContributionBtn:
MsgBox Err.Number & Err.Description
Resume Exit_AddContributionBtn
End Sub
For DLookup():
varCurrency = DLookup("NetAssetValue", "NAV_Tbl", "NAV_Date >= #" & Format(CurrentNAVDate, "yyyy-mm-dd") & "#")