I've got myself in trouble working with attachments. I wanted to be able to duplicate a record for easy entry but I am stuck. The RegNo on the database is a unique field that does not allow duplicates. The expectation is that I copy all the data to a form and SetFocus on txtRegNo so that a user can input this information before the record is saved. Is this even possible in Access or am I just wasting my time? Please see my code below. I have also attached images. Your help and guidance is highly appreciated:
Private Sub btnDuplicateRecord_Click()
Me![Make].DefaultValue = "'" & Me![Make] & "'"
Me![Model].DefaultValue = "'" & Me![Model] & "'"
Me![EngineSize].DefaultValue = "'" & Me![EngineSize] & "'"
Me![Qty].DefaultValue = "'" & Me![Qty] & "'"
Me![MOTDue].DefaultValue = "'" & Me![MOTDue] & "'"
Me![MarketValue].DefaultValue = "'" & Me![MarketValue] & "'"
Me![VehicleImage].DefaultValue = "'" & Me![VehicleImage] & "'"
DoCmd.RunCommand acCmdRecordsGoToNew
txtRegNo.SetFocus
End Sub
Another try:
Dim db As DAO.Database
Dim rsParent As DAO.Recordset2
Dim rsChild As DAO.Recordset2
Dim strSQL As String
Set db = CurrentDb
strSQL = "SELECT * FROM tblCars"
Set rsParent = db.OpenRecordset(strSQL)
Set rsChild = rsParent.Fields("VehicleImage").Value
rsParent.Edit
DoCmd.RunCommand acCmdRecordsGoToNew
rsChild.AddNew
rsChild.Fields("FileData") = rsChild.Fields("FileData")
rsChild.Fields("FileName") = rsChild.Fields("FileName")
'rsChild.Update
'rsParent.Update
RegNo.SetFocus
I'm running into some issues with my update statement, the Add statement seems to work but I keep getting a syntax error in update. I am new to SQL and VBA so a lot of this probably looks like sphagetti code. If anyone can Identify what I did wrong that would be much appreciated. If there is a better way to do it, please let me know.
Private Sub btnSubmit_Click()
Dim mbrName As String
Dim mbrOffice As String
Dim mbrRank As String
Dim mbrOpType As String
Dim mbrRLA As String
Dim mbrMQT As String
Dim mbrPos As String
Dim sqlAdd As String
Dim sqlUpdate As String
If Me.opgMngRoster.Value = 1 Then
'-Set Middle Name to NMI if blank
If IsNull(Me.txtMidInit.Value) Then
Me.txtMidInit.Value = "NMI"
End If
'-Create Member's Name string in all uppercase
mbrName = UCase(Me.txtLastName.Value & ", " & Me.txtFirstName.Value & " " & Me.txtMidInit)
'-Member's Office
mbrOffice = Me.cbxOffice.Value
'-Member's Rank
mbrRank = Me.cbxRank.Value
'-Member's Operator Type
mbrOpType = Me.cbxOpType
'-Member's RLA
mbrRLA = Me.cbxRLA.Value
'-Member's MQT Program
mbrMQT = Me.cbxMQT.Value
'-Member's MQT Position
mbrPos = Me.cbxTngPos.Value
'ADD MEMBER TO ROSTER
sqlAdd = "INSERT INTO [ROSTER] (MEMBER, OFFICE, RANK, OPTYPE, RLA, [MQT-PROGRAM], [MQT-POSITION]) VALUES ('" & mbrName & "', '" & mbrOffice & "', '" & mbrRank & "', '" & mbrOpType & "', '" & mbrRLA & "', '" & mbrMQT & "', '" & mbrPos & "');"
DoCmd.RunSQL (sqlAdd)
'-Confirmation Msg
MsgBox ("Added: " & mbrName)
Else
'-Set Middle Name to NMI if blank
If IsNull(Me.txtMidInit.Value) Then
Me.txtMidInit.Value = "NMI"
End If
'-Create Member's Name string in all uppercase
mbrName = UCase(Me.txtLastName.Value & ", " & Me.txtFirstName.Value & " " & Me.txtMidInit)
'-Member's Office
mbrOffice = Me.cbxOffice.Value
'-Member's Rank
mbrRank = Me.cbxRank.Value
'-Member's Operator Type
mbrOpType = Me.cbxOpType
'-Member's RLA
mbrRLA = Me.cbxRLA.Value
'-Member's MQT Program
mbrMQT = Me.cbxMQT.Value
'-Member's MQT Position
mbrPos = Me.cbxTngPos.Value
'Update Member Data
sqlUpdate = "UPDATE [ROSTER] (MEMBER, OFFICE, RANK, OPTYPE, RLA, [MQT-PROGRAM], [MQT-POSITION]) VALUES ('" & mbrName & "', '" & mbrOffice & "', '" & mbrRank & "', '" & mbrOpType & "', '" & mbrRLA & "', '" & mbrMQT & "', '" & mbrPos & "');"
Debug.Print sqlUpdate
DoCmd.RunSQL sqlUpdate
MsgBox ("Updated: " & mbrName)
End If
End Sub
Several general coding and specific MS Access issues with your setup:
First, no need to repeat your VBA variable assignments for both If and Else blocks. Use DRY-er code (Don't Repeat Yourself).
Also, since you do not apply further calculations, there is no need to assign the majority of form textbox and combobox values to separate string variables. Use control values directly in query.
Use parameterization (an industry best practice) which is not only for MS Access but anywhere you use dynamic SQL in an application layer (VBA, Python, PHP, Java, etc.) for any database (Postgres, SQL Server, Oracle, SQLite, etc.). You avoid injection and any messy quote enclosure and data concatenation.
While languages have different ways to bind values to parameters, one way in MS Access is to use querydef parameters as demonstrated below.
Save your queries as stored objects with PARAMETERS clause (only compliant in MS Access SQL dialect). This helps abstract code from data.
Finally, properly use the update query syntax: UPDATE <table> SET <field>=<value> ...
Insert SQL Query (with parameterization, save once as stored query)
PARAMETERS MEMBER_Param TEXT, OFFICE_Param TEXT, RANK_Param TEXT, OPTYPE_Param TEXT,
RLA_Param TEXT, MQT_PROGRAM_Param TEXT, MQT_POSITION_Param TXT;
INSERT INTO [ROSTER] (MEMBER, OFFICE, RANK, OPTYPE, RLA, [MQT-PROGRAM], [MQT-POSITION])
VALUES (MEMBER_Param, OFFICE_Param, RANK_Param, OPTYPE_Param,
RLA_Param, MQT_PROGRAM_Param, MQT_POSITION_Param);
Update SQL Query (with parameterization, save once as stored query)
PARAMETERS MEMBER_Param TEXT, OFFICE_Param TEXT, RANK_Param TEXT, OPTYPE_Param TEXT,
RLA_Param TEXT, MQT_PROGRAM_Param TEXT, MQT_POSITION_Param TXT;
UPDATE [ROSTER]
SET MEMBER = MEMBER_Param, OFFICE = OFFICE_Param, RANK = RANK_Param,
OPTYPE = OPTYPE_Param, RLA = RLA_Param, [MQT-PROGRAM] = MQT_PROGRAM_Param,
[MQT-POSITION] = MQT_POSITION_Param;
VBA (no SQL shown)
Dim mbrName As String, myquery As String, mymsg As String
Dim qdef As QueryDef
'-Set Middle Name to NMI if blank
If IsNull(Me.txtMidInit.Value) Then
Me.txtMidInit.Value = "NMI"
End If
'-Create Member's Name string in all uppercase
mbrName = UCase(Me.txtLastName.Value & ", " & Me.txtFirstName.Value & " " & Me.txtMidInit)
If Me.opgMngRoster.Value = 1 Then
myquery = "myRosterInsertQuery"
mymsg = "Added: " & mbrName
Else
myquery = "myRosterUpdateQuery"
mymsg = "Updated: " & mbrName
End If
' ASSIGN TO STORED QUERY
Set qdef = CurrentDb.QueryDefs(myquery)
' BIND PARAMS
qdef!MEMBER_Param = mbrName
qdef!OFFICE_Param = Me.cbxOffice.Value
qdef!RANK_Param = Me.cbxRank.Value
qdef!OPTYPE_Param = Me.cbxOpType
qdef!RLA_Param = Me.cbxRLA.Value
qdef!MQT_PROGRAM_Param = Me.cbxMQT.Value
qdef!MQT_POSITION_Param = Me.cbxTngPos.Value
qdef.Execute dbFailOnError
'-Confirmation Msg
MsgBox mymsg, vbInformation
Set qdef = Nothing
I've been poking around with the below code and cannot get it to work.
Dim db As Database
Dim RecRLs As Recordset
Dim sTripCode, sVanNum As Integer
Dim sDepDate, sArrivalDate As Date
Dim sRoomRate As Currency
Set RecRLs = db.OpenRecordset("qryRLRoomListRates", dbOpenSnapshot)
sTripCode = DLookup("[TourCodeID]", "tblTripCodes", "[TourCode]=[Forms]![frmRMSBuildRLs]![tboxTourCode]")
sDepDate = [Forms]![frmRMSBuildRLs]![tboxDepartureDate]
sVanNum = [Forms]![frmRMSBuildRLs]![tboxVanNumber]
sArrivalDate = RecRLs!ArrivalDate
sRoomRate = DLookup("[RateTwinHosCab]", "tblRLRatesByTrip", "[TourCode] = "
& sTripCode & " AND [DepartureDate] = " & sDepDate & " AND [VanNumber] = " &
sVanNum & " AND [ArrivalDate] = " & sArrivalDate)
The issue is that sRoomRate returns null.
I've MsgBox'd each of the variables: sTripCode, sDepDate, sVanNum, and sArrivalDate. They each return the correct result.
Any ideas why sRoomRate would return null? Thank you so much!
The solution was to add the #s around the dates below:
sRoomRate = DLookup("[RateTwinHosCab]", "tblRLRatesByTrip", "[TourCode] = " &
sTripCode & " AND [DepartureDate] = #" & sDepDate & "# AND [VanNumber] = " &
sVanNum & " AND [ArrivalDate] = #" & sArrivalDate & "#")
I have a problem that when I try updating data the the program doesn't save it in the database.
This is the current code:
Dim y As Byte = Convert.ToByte(lblID.Text) - 1
Dim cb As New OleDb.OleDbCommandBuilder(da)
ds.Tables("dset").Rows(y).Item(1) = txtname.Text
ds.Tables("dset").Rows(y).Item(2) = txtsubm.Text & "/" & txtsubd.Text & "/" & txtsuby.Text
ds.Tables("dset").Rows(y).Item(3) = txtexpm.Text & "/" & txtexpd.Text & "/" & txtexpy.Text
ds.Tables("dset").Rows(y).Item(5) = txtnotes.Text
If MdComboBox1.SelectedItem = "A" Then
ds.Tables("dset").Rows(y).Item(4) = "A"
ElseIf MdComboBox1.SelectedItem = "B" Then
Else
MdAlertBox1.Text = "Please Select A Class The Class Box"
MdAlertBox1.Visible = True
End If
MdAlertBox1.Text = "Data Sucessfully Updated !"
MdAlertBox1.kind = MDAlertBox._Kind.Success
MdAlertBox1.Visible = True
getinfo.Start()
updatedata.Stop()
And the declared variables:
Dim conn As New OleDb.OleDbConnection
Dim DbProv As String = "PROVIDER=microsoft.ACE.OLEDB.12.0;"
Dim Src As String = " data source = c:\users\kingo\documents\visual studio 2013\Projects\WindowsApplication2\WindowsApplication2\BigGymDB.accdb"
Dim da As OleDb.OleDbDataAdapter
Dim ds As New DataSet
Put a debug.print to see the values you are passing to the Database. Like this:
ds.Tables("dset").Rows(y).Item(2) = txtsubm.Text & "/" & txtsubd.Text & "/" & txtsuby.Text
ds.Tables("dset").Rows(y).Item(3) = txtexpm.Text & "/" & txtexpd.Text & "/" & txtexpy.Text
ds.Tables("dset").Rows(y).Item(5) = txtnotes.Text
'your code ---^
debug.print txtname.Text; txtsubm.Text & "/" & txtsubd.Text & "/" & txtsuby.Text;
debug.print txtnotes.Text; txtexpm.Text & "/" & txtexpd.Text & "/" & txtexpy.Text
'your code ---v
If MdComboBox1.SelectedItem = "A" Then
ds.Tables("dset").Rows(y).Item(4) = "A"
ElseIf MdComboBox1.SelectedItem = "B" Then
Then in two lines in the Immdiate Window, you should see whether these txtsub.Text and the other 3 inputs actually have something.
I have a gridview that fills with data, and a view button which gives more details of the record choosen by the user. I cannot figure out why I am getting the error:
Object reference not set to a instance of an Object
I have narrowed it down to between my two message boxes. The First message box comes up but it crashes before the second. Any suggestions would be greatly appreciated.
Protected Sub CountAlerts_RowCommand(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewCommandEventArgs) Handles CountAlerts.RowCommand
If (e.CommandName = "Viewdtails") Then
Dim index As Integer = Convert.ToInt32(e.CommandArgument)
Dim NDC, Unit, Cell, DTTM, prod, Query, _startdt, _enddt As String
Dim DS As DataSet
NDC = CountAlerts.DataKeys(index).Values("NDC")
Cell = CountAlerts.DataKeys(index).Values("Cell")
Unit = CountAlerts.DataKeys(index).Values("Unit")
DTTM = CountAlerts.DataKeys(index).Values("TimeDate")
prod = CountAlerts.DataKeys(index).Values("ProductDesc")
_startdt = If(StartDate.Text = "", DateAdd(DateInterval.Day, -7, System.DateTime.Now).ToShortDateString, StartDate.Text)
_enddt = If(EndDate.Text = "", System.DateTime.Now.ToShortDateString, EndDate.Text)
For Each irow As GridViewRow In CycleCountAlerts.Rows
If irow.Attributes("class") = "highlight" Then
irow.Attributes.Remove("class")
End If
Next
CountAlerts.Rows(index).Attributes("class") = "highlight"
Query = " EXEC [Audits].[dbo].[ExceptionDetailsCombined] '" & NDC & "', '" & Cell & "', '" & Unit & "', '" & DTTM & "', '" & Master.CF_User.Viewing & "' "
DS = SelectQuery(Query)
If (DS.Tables.Count > 0) Then
unitbox.Text = DS.Tables(0).Rows(0)("Unit")
cellbx.Text = DS.Tables(0).Rows(0)("Cell")
ndcbox.Text = DS.Tables(0).Rows(0)("NDC")
namebox.Text = DS.Tables(0).Rows(0)("ProductDesc")
cycdttmbx.Text = DS.Tables(0).Rows(0)("TimeDate")
cycusr.Text = DS.Tables(0).Rows(0)("CycUser")
todisp.Text = DS.Tables(0).Rows(0)("TODISPSIZE")
topkgbox.Text = DS.Tables(0).Rows(0)("TOPKGSIZE")
toqtybx.Text = DS.Tables(0).Rows(0)("TOQTY")
FRQTYbx.Text = DS.Tables(0).Rows(0)("FRQTY")
TextBox2.Text = DS.Tables(0).Rows(0)("ActualQTY")
cycvarqbox.Text = DS.Tables(0).Rows(0)("CYCLEVARQTY")
CycleVarPctbx.Text = DS.Tables(0).Rows(0)("CYCLEVARPCT")
alertrsnbx.Text = DS.Tables(0).Rows(0)("AlertReason")
combox.Text = DS.Tables(0).Rows(0)("AcceptComment")
acusr.Text = DS.Tables(0).Rows(0)("AcceptUser")
acctime.Text = DS.Tables(0).Rows(0)("AcceptTime")
accstatbx.Text = DS.Tables(0).Rows(0)("AcceptStatus")
displbl.Text = DS.Tables(0).Rows(0)("Disposition")
End If
Query = " EXEC [CF_Audits].[dbo].[CommentTrackerCombined] '" & Master.CF_User.EmployeeID & "', '" & NDC & "', '" & Cell & "', '" & Unit & "', '" & _startdt & "', '" & _enddt & "', '" & Master.CF_User.Viewing & "' "
DS = SelectQuery(Query)
If (DS.Tables.Count > 0) Then
ExceptionHist_GV.DataSource = DS
ExceptionHist_GV.DataBind()
ExceptionHist_GV.UseAccessibleHeader = True
MsgBox("except gv header") 'Runs up to here.
ExceptionHist_GV.HeaderRow.TableSection = TableRowSection.TableHeader
MsgBox("except gv header 2") ' Does not make it to here.
End If
End If
End Sub
Most likely TableRowSection or TableRowSection.TableHeader is/are Nothing
Check that these are initialised before using them
If MsgBox("except gv header")
If Not TableRowSection Is Nothing AndAlso Not TableRowSection.TableHeader Is Nothing Then
ExceptionHist_GV.HeaderRow.TableSection = TableRowSection.TableHeader
Else
MsgBox "How did we get here?"
End If
MsgBox("except gv header 2")
If you see the message "How did we get here" that indicates you have not initialised you object
In object orientated languages you need to instantiate an object before you can use it.
Something in this line:
ExceptionHist_GV.HeaderRow.TableSection = TableRowSection.TableHeader
has not been instantiated with the new keyword. You can find out exactly what by checking the details of the Exception which was thrown.
It will be either ExceptionHist_GV or TableRowSection.