I am trying to add a record to a record set through a form. one of the fields in the form is an attachment. How can i add the attachment into the record set as I keep receiving errors of "Data Type Mismatch"? I understand the attachment field is basically a record set with "FileData","FileName", "File Type" Fields, but how can i have vba add the attachment from the form I have to the record set??
below is the coding I use:
Private Sub Command31_Click()
Dim Db As Database
Dim rs As DAO.Recordset
Dim rs2 As DAO.Recordset
Set Db = CurrentDb
Dim Message1, Message2, Title1, Default, MyValue1, MyValue2
Dim SN
Dim q As Long
Dim i As Long
Message1 = "ENTER TOTAL QUANTITY RECEIVED OF " & Me.Item ' Set prompt.
Title1 = "Total Quantity Received" ' Set title.
Default = "1" ' Set default.
' Display message, title, and default value.
MyValue1 = InputBox(Message1, Title1, Default)
i = 0
q = MyValue1
Do While (i < q)
Message2 = "ENTER S/N FOR ITEM NUMBER " & i + 1 ' Set prompt.
Title2 = "SERIAL NUMBER ENTRY" ' Set title.
Default = "1" ' Set default.
' Display message, title, and default value.
MyValue2 = InputBox(Message2, Title2, Default)
Set rs = Db.OpenRecordset("Inventory Transactions")
rs.Edit
rs.AddNew
Set rs2 = rs.Fields("Transaction Docs").Value
rs.Fields("Tx Date") = Date
rs.Fields("Project Code") = Me.Project_Code
rs.Fields("Transaction Type") = 1
rs.Fields("Transaction Item") = Me.Item
rs.Fields("Reference Document") = Me.Reference_Document
rs.Fields("Serial Number") = MyValue2
rs.Fields("Quantity") = 1
rs.Fields("Location") = Me.Location
rs.Fields("Entered by") = Me.Entered_by
rs.Fields("Recepient") = Me.Recepient
rs2.AddNew
rs2.Fields("FileData").LoadFromFile (Me.Transaction_Docs)
rs2.Update
'With rsatt1
'Do While Not rsatt1.EOF
'rsatt1.AddNew
'rsatt1.Fields("FileData") = rsatt1.Fields("FileData")
'rsatt1.Fields("FileName") = rsatt1.Fields("FileName")
'rsatt1.Fields("FileType") = rsatt1.Fields("FileType")
'rsatt1.Update
'.MoveNext
'Loop
'End With
'rsatt1.Close
Set rs2 = Nothing
rs.Update
rs.Close
i = i + 1
Loop
Set rs = Nothing
DoCmd.Close
DoCmd.OpenForm "MULTIPLE RECORDS GENERATOR"
DoCmd.Requery
Db.Close
End Sub
Related
I am trying to find a way to move the data from a query to a table in MS Word. I have attached a picture of the document
Here's the situation: When we close a case out, we need to create a document that includes several pieces of demographic data from that case and list of important dates to that case. The table needs to have some borders (underline on the date), and it needs to be inserted midway through the document (I am thinking bookmarks are the way to go). The document may be sent to other providers off of our network. (I am really hoping the pic attached...)
I have tried using Power Query (which does not allow the user to set parameters or prompt for criteria).
My initial thoughts are to create a recordset from the query and then create a loop to insert the data into the table. However, all the posts I could find seem to only deal with creating the table in word as the sole object. I also can't find how to point the recordset to a bookmark or particular table. The user will generate the document from Access (Right now, I have it where it will put certain dates, like open and close, into the corresponding Form Field in Word template, but I'm stuck at this juncture).
I have minor programming knowledge, just enough to be known as the local expert, when I am merely the only programming fish in the small pond. I would be happy to pointed in the right direction or given some code snippets (I would like to understand why/how they work).
With gratitude, I want to post the code for the solution. Of course, there is probably a better way to do it, but the solution works, and best of all I know why it works.
Public Function concatData() As String
Dim retVal As String
Dim rsHeader As Long, rsCounter As Long
Dim rs As DAO.Recordset
Dim Val As String
Dim strSQL As String
'This code puts the query into a recordset, which is then formatted into a table later
Val = [Forms]![FrmAllTracker]![CaseID]
strSQL = "Select * From QryTrackerInitRecRecv WHERE [CaseID] = " & Val
Set rs = CurrentDb.OpenRecordset(strSQL)
'Get headers
'For rsHeader = 0 To rs.Fields.Count - 1
' retVal = retVal & rs.Fields(rsHeader).Name & vbTab
'Next
'Replace last TAb with a carriage return
'retVal = Left(retVal, Len(retVal) - 1) & vbCr
Do While Not rs.EOF
'Get all records
For rsCounter = 0 To rs.Fields.Count - 1
retVal = retVal & rs.Fields(rsCounter).Value & vbTab
Next
retVal = Left(retVal, Len(retVal) - 1) & vbCr
rs.MoveNext
Loop
concatData = retVal
End Function
Private Sub BtnGenTracker_Click()
If IsNull(Me.CaseClosed) Then
MsgBox "Please Enter a Close Date", _
vbOKOnly + vbInformation
Exit Sub
End If
' Create pointers to Word Document
Dim wd As Word.Application
Dim doc As Word.Document 'doc As Word.Document
Dim bolOpenedWord As Boolean
Dim rng As Range
Dim Tbl As Word.Table
Dim MDate As String
MDate = Format([CaseOpen], "mm-dd-yyyy")
' Get pointer to Word Document
On Error Resume Next
Set wd = GetObject(, "Word.Application")
If Err.Number = 429 Then
' If Word is not opened, open it
Set wd = CreateObject("Word.Application")
bolOpenedWord = True
End If
wd.Visible = True ' Set this to true if you want to see the document open
On Error GoTo 0
Set doc = wd.Documents.Add("\\gsmstore2\COE\Testing Database\TFT1.docx")
DoCmd.OpenForm FormName:="FrmRelRecSenAll"
With doc
On Error Resume Next
'sends particular fields to corresponding FormFields in Word
.FormFields("PtName").Result = [Forms]![FrmAllTracker]![FrmSubTherapyRef].[Form].[Text62]
.FormFields("COENum").Result = Me.COEMR
.FormFields("RefRec").Result = Me.CaseOpen
.FormFields("FirstCont").Result = Me.CaseOpen
.FormFields("InitRecsRecv").Result = DLookup("FirstOfRecordsRec", "QryTrackerInitRecRecvCFFirst")
.FormFields("SuffRecs").Result = Me.SuffRecDate
.FormFields("Init2").Result = Me.InitCaseDate
.FormFields("TeamRev").Result = DLookup("ContactDate", "QryTrackerTeamRev", "[ContactType] = 14")
.FormFields("MCRMeet").Result = DLookup("ContactDate", "QryTrackerTeamRev", "[ContactType] = 6")
.FormFields("MCRMeetAct").Result = DLookup("ContactDate", "QryTrackerTeamRev", "[ContactType] = 6")
.FormFields("FTDate").Result = InputBox("Please enter Date of FT Release", "FT Release", Default)
.FormFields("FirstAppt").Result = InputBox("Please enter Date of 1st offered appt", "1st Offered Date", Default)
.FormFields("AssessDebrief").Result = DLookup("ContactDate", "QryTrackerTeamRev", "[ContactType] = 15")
.FormFields("RptSent").Result = DLookup("ContactDate", "QryTrackerTeamRev", "[ContactType] = 11")
.FormFields("FFollow").Result = DLookup("ContactDate", "QryTrackerTeamRev", "[ContactType] = 12")
.FormFields("LFollow").Result = DLookup("ContactDate", "QryTrackerLFollow")
.FormFields("CaseClosed").Result = Me.CaseClosed
If Not IsNull(DLookup("ContactDate", "QryTrackerTeamRev", "[ContactType] = 4")) Then
.FormFields("Bill").Result = "Yes"
Else
.FormFields("Bill").Result = "No"
End If
.Application.Activate
Set rng = ActiveDocument.Bookmarks("Releases").Range
rng.Text = concatData()
Set Tbl = rng.ConvertToTable
End With
'This foramats the table
With Tbl
.Columns(1).Borders(wdBorderBottom).LineStyle = wdLineStyleSingle
.Columns(1).Borders(wdBorderBottom).LineWidth = wdLineWidth050pt
.Columns(1).Borders.InsideLineStyle = wdLineStyleSingle
.Columns(1).Borders.InsideLineWidth = wdLineWidth050pt
.Columns(1).Width = 125
.Columns(2).Width = 450
.Columns(3).Delete
End With
wd.ActiveDocument.SaveAs2 ("\\Filelocation\COE\Case Files\" & COEMR & "\Tracking Sheet" & " " & MDate & ".docx")
Set doc = Nothing
Set wd = Nothing
Set rg = Nothing
Set Tbl = Nothing
End Sub
I've been out of Access for a bit, and having some trouble with a somewhat simple concept. I want to loop through the records of a subform and adjust inventory numbers after a sale. The looping through the subform tested fine, but when I tried to add the bit about adjusting inventory I received a Method or Data Member Not Found error. For S&G's, I pasted the SQL into an empty query and it returned the data just fine. I must not be DIM-ing something right? The error comes when it attempts to set rec2 = db.OpenRecordset. The error falls specifically on rec2.StockQuantity, but as I've said the field exists when I just paste the rec2 code into an empty query.
Here's the full code:
Option Compare Database
Option Explicit
Private Sub bnUpdate_Click()
Dim db As Database
Dim rec As Recordset
Dim rec2 As Recordset
Dim MsgBx1 As String
Dim X As String
Dim Y As String
Me.Refresh
Me.Parent.Refresh
Me.Parent!TotalSale.Value = Me.txtPriceSum.Value
MsgBx1 = MsgBox("Do you want to save the record?", vbYesNo, "Save Sale")
If MsgBx1 = vbYes Then
Set rec = Me.Form.Recordset
Do While rec.EOF = False
X = Me.UPC
Set rec2 = db.OpenRecordset("Select SKU, StockQuantity from tblProduct where SKU = '" & X & "'")
rec2.Edit
Y = rec2.StockQuantity
rec2.StockQuantity = Y - 1
rec2.Update
Set rec2 = Nothing
'MsgBox X
rec.MoveNext
Loop
Else
End If
End Sub
Try this with a lot of modifications:
Private Sub bnUpdate_Click()
Dim rec As DAO.Recordset
Dim rec2 As DAO.Recordset
Dim MsgBx1 As Long
Dim X As String
Dim Y As Long
Me.Refresh
Me.Parent.Refresh
Me.Parent!TotalSale.Value = Me!txtPriceSum.Value
MsgBx1 = MsgBox("Do you want to save the record?", vbQuestion + vbYesNo, "Save Sale")
If MsgBx1 = vbYes Then
Set rec = Me.RecordsetClone
rec.MoveFirst
Do While rec.EOF = False
X = rec!UPC.Value
Set rec2 = CurrentDb.OpenRecordset("Select SKU, StockQuantity from tblProduct where SKU = '" & X & "'")
Y = rec2!StockQuantity.Value
rec2.Edit
rec2!StockQuantity.Value = Y - 1
rec2.Update
rec2.Close
rec.MoveNext
Loop
rec.Close
End If
End Sub
I've created a form where I can use a subform to load data from a query into textboxes so I can edit the data one at a time and update the database. This usually works fine except I have a run time error that randomly appears now and then - '-2147352567 (80020009)': The value you entered isn't valid for this field.'
If I stop running it and try running it again it usually works fine until the same run-time error appears. It's very inconsistent.
Private Sub btn_SelectAgency_Click()
If Not (Me.qryAgencyWithoutMileagesub.Form.Recordset.EOF And Me.qryAgencyWithoutMileagesub.Form.Recordset.BOF) Then
'get data to textbox control
With Me.qryAgencyWithoutMileagesub.Form.Recordset
Me.txt_AgencyID = .Fields("Agency ID")
Me.txt_AgencyName = .Fields("Agency Name")
Me.txt_Address1 = .Fields("Address 1")
Me.txt_Address2 = .Fields("Address 2")
Me.txt_City = .Fields("City")
Me.txt_Postcode = .Fields("Postcode")
Me.txt_AgencyMileage = .Fields("Mileage")
Me.txt_AgencyID.Tag = .Fields("Agency ID")
End With
End If
Me.txt_AgencyMileage = ""
End Sub
Private Sub btn_Update_Click()
If Me.txt_AgencyMileage = "" Then
MsgBox "No mileage added, add now"
Cancel = True
Else
CurrentDb.Execute "UPDATE EstateAgent_tbl SET EstateAgent_AgentMileage = '" & Me.txt_AgencyMileage & "' where EstateAgent_AgentID=" & Me.txt_AgencyID.Tag
Me.txt_AgencyID = ""
Me.txt_AgencyName = ""
Me.txt_Address1 = ""
Me.txt_Address2 = ""
Me.txt_City = ""
Me.txt_Postcode = ""
Me.txt_AgencyMileage = ""
End If
qryAgencyWithoutMileagesub.Form.Requery
If Me.qryAgencyWithoutMileagesub.Form.Recordset.RecordCount = 0 Then
MsgBox "No agencies without mileage"
DoCmd.Close
End If
End Sub
The error is on this line
Me.txt_AgencyID = .Fields("Agency ID")
I would appreciate any help with this, thank you :)
Dim rs As DAO.Recordset
Set rs = Me.qryAgencyWithoutMileagesub.Form.RecordsetClone
'get data to textbox control
With rs
If .RecordCount > 0 Then
Me.txt_AgencyID = .Fields("Agency ID")
Me.txt_AgencyName = .Fields("Agency Name")
Me.txt_Address1 = .Fields("Address 1")
Me.txt_Address2 = .Fields("Address 2")
Me.txt_City = .Fields("City")
Me.txt_Postcode = .Fields("Postcode")
Me.txt_AgencyMileage = .Fields("Mileage")
Me.txt_AgencyID.Tag = .Fields("Agency ID")
End If
End With
Set rs = Nothing
DoCmd.RefreshRecord
DoCmd.RunCommand acCmdUndo
'You can it try. That worked for me!
Try to exclude Null values:
If Not IsNull(.Fields("Agency ID").Value) Then
Me.txt_AgencyID.Value = .Fields("Agency ID").Value
End If
You may also try using the RecordsetClone:
Dim rs As DAO.Recordset
Set rs = Me.qryAgencyWithoutMileagesub.Form.RecordsetClone
'get data to textbox control
With rs
If .RecordCount > 0 Then
Me.txt_AgencyID = .Fields("Agency ID")
Me.txt_AgencyName = .Fields("Agency Name")
Me.txt_Address1 = .Fields("Address 1")
Me.txt_Address2 = .Fields("Address 2")
Me.txt_City = .Fields("City")
Me.txt_Postcode = .Fields("Postcode")
Me.txt_AgencyMileage = .Fields("Mileage")
Me.txt_AgencyID.Tag = .Fields("Agency ID")
End If
End With
Set rs = Nothing
I am trying to do a query of a linked table. After I get the results, I need to do 1 of 2 things. Either say it passed or failed. Here is the code I have written. It doesn't give me any errors, nor does it run correctly. When I input a SN I know doesn't have any entries it doesn't run the second part (the fail part).
Private Sub SQL_Check()
Dim rs As DAO.Recordset
Dim sqlMax As String
Dim result As String
sqlMax = "Select count(1) FROM dbo_Event WHERE [AssemblyNo] = 'SYSCHATESTE' and [SerialNo] = '" & Me.txtUnitNo & "' and [ProcessTyp] = 'SF1';"
Set rs = CurrentDb.OpenRecordset(sqlMax)
If rs.Fields.Count = 1 Then
txtECCT.BackColor = vbGreen
txtECCT.ForeColor = vbBlack
txtECCT.Value = "Passed"
GoTo la
End If
If rs.Fields.Count = 0 Then
Set rs = Nothing
Set db = CurrentDb
Set rec = db.OpenRecordset("Select * from tblScannedParts")
rec.AddNew
rec("Inspector") = Me.txtUserId
rec("PO Number") = Me.txtWorkOrderNo
rec("Assembly") = Me.txtAssem
rec("SERIAL Number") = Me.txtUnitNo
rec("DateScanned") = CStr(Now())
rec("Result") = "Failed"
rec("Defect Type") = "Missing ECCT"
rec("Comments") = strFileContent
rec("Qty") = "1"
rec.Update
txtStatus.BackColor = vbRed
txtStatus.ForeColor = vbBlack
txtStatus.Value = "Failed"
MsgBox "Please take unit to NCM Cart for review.", vbCritical, "Unit Not Ready for DOF QA"
txtAssem.SetFocus
End If
la:
Set rs = Nothing
End Sub
The issue is that the recordset rs is based on a SELECT which returns one field, so your If condition, rs.Fields.Count = 1, will always be True.
Conversely, the code within the If rs.Fields.Count = 0 Then block could never run because Fields.Count would never be zero. And actually, Access does not even evaluate that condition because you included GoTo la in the previous If block ... which quickly exits the procedure. Be wary of GoTo
If you want to base the action on a count of matching records, I think the logic should be simpler with DCount().
Dim strCriteria As String
Dim lngMatchCount As Long
strCriteria = "[AssemblyNo] = 'SYSCHATESTE' AND [SerialNo] = '" & Me!txtUnitNo.Value & "' AND [ProcessTyp] = 'SF1'"
Debug.Print strCriteria '<- inspect this in Immediate window; Ctrl+g will take you there
lngMatchCount = DCount("*", "dbo_Event", strCriteria)
If lngMatchCount > 0 Then
' do the 'Passed' thing
Else
' do the 'Failed' thing
End If
I have an access database with vba code that is attempting to access an excel sheet and copy the data to a recordset using DAO.recordset. If all of the column (assocId) is integer the import works wonderfully if all are strings it works but if you have a mixed back (eg 111111 | Vinny | etc and then on row two you have JOE-1 | Joe | etc) the import will fail. It says "You cannot record your changes because a value you entered violates the settings defined for this table"
Here is the offending sub:
Public Sub LoadFileInfo()
'Load information from selected file
On Error GoTo ErrorHappened
Dim db As DAO.Database
Dim rs As DAO.Recordset
Dim i As Integer
Dim lastTransType As String
Dim transactionCounter As Integer
Dim currentRecord As CurrentImportRecord
Dim wtf As Variant
Set db = CurrentDb()
Set rs = db.OpenRecordset(selectTransTypesSql & GetSetting("PayrollManualImportExportTransactionTypes") & ")")
ReDim transTypes(DCount("TransType", "MasterTransactionTypes", "IsActive <> 0")) As MasterTransactionTypes
rs.MoveFirst
Do While Not rs.EOF
'Add each transaction type and desc to the Private Type and increment the appropriate counter
GetMasterTransactionTypes rs!TransType, rs!TransDesc, i
rs.MoveNext
i = i + 1
Loop
rs.Close
Set db = OpenDatabase(importFileName, False, True, "Excel 12.0;HDR=Yes")
Set rs = db.OpenRecordset("SELECT * FROM " & "[" & GetSheetName(importFileName) & "$]" & " ORDER BY TransType")
rs.MoveLast
importFields = vbNullString
For i = 0 To rs.Fields.count - 1
importFields = importFields & rs.Fields(i).Name & ","
Next
fullImport = (rs.Fields.count > 4)
i = 0
transactionCounter = 1
lblFile.Caption = "File name: " & importFileName
Dim rowNum As Variant
rowNum = rs.RecordCount
wtf = rs.GetRows(rowNum)
ReDim ledgerEntries(rs.RecordCount) As PayrollLedgerImport
'Check to see if the recordset actually contains rows; if so push transaction objects to private type array
rs.MoveFirst
Do While Not rs.EOF
currentRecord.associateId = CStr(rs!assocId)
currentRecord.transactionType = rs!TransType
currentRecord.transactionNotes = CStr(rs!TransNotes)
If lastTransType = CStr(currentRecord.transactionType) Then
transactionCounter = transactionCounter + 1
Else
transactionCounter = 1
End If
If IsValidTransType(currentRecord.transactionType) Then
If Not fullImport Then
currentRecord.transactionAmount = rs!TransAmount
GetPayrollTransactions currentRecord.associateId, currentRecord.transactionType, currentRecord.transactionAmount, currentRecord.transactionNotes, i, transactionCounter
Else
currentRecord.transactionAmount = rs!TransAmt
GetPayrollTransactions currentRecord.associateId, currentRecord.transactionType, currentRecord.transactionAmount, currentRecord.transactionNotes, i, transactionCounter
End If
Else
MsgBox (currentRecord.transactionType & ": Not A Valid Transaction Type")
End If
lastTransType = rs!TransType
rs.MoveNext
i = i + 1
Loop
FormatFileInformationWindow
cmdImportFile.Enabled = True
End Sub
I've been at this for hours. I've tried casting all the columns when I take them in and I get the same issue. Works fine for all ints or all strings but in reality some of our employees have string and some have int for employee ID. I tried taking them all in as string converting where necessary but that didn't work either. Only thing that works is two sheets - one containing strings one containing ints.