I have added DoCmd.Close acQuery, "Import", acSaveNo
And my access window doesn't close even with this line of code.
Option Compare Database
Option Explicit
Public Function Import()
Dim dbs As DAO.Database
Dim rst As DAO.Recordset
Dim intFile As Integer
Dim strFilePath As String
Dim intCount As Integer
Dim strHold
strFilePath = "C:\Transfer\FromSynapseTest\TEST.csv"
Set dbs = CurrentDb
Set rst = dbs.OpenRecordset("Import", dbOpenForwardOnly)
intFile = FreeFile
Open strFilePath For Output As #intFile
Do Until rst.EOF
If CDate(rst(3)) >= Date And rst(98) <> 0 Then
For intCount = 0 To rst.Fields.Count - 1
strHold = strHold & rst(intCount).Value & "|"
Next
If Right(strHold, 1) = "|" Then
strHold = Left(strHold, Len(strHold) - 1)
End If
Print #intFile, strHold
End If
rst.MoveNext
strHold = vbNullString
Loop
Close intFile
rst.Close
Set rst = Nothing
DoCmd.Close acQuery, "Import", acSaveNo
End Function
Since I'm calling the function by macro, I don't think I can do
Sub subToCloseForm
DoCmd.Close
End Sub
Also I have tried DoCmd.Close acQuery, " ", acSaveNo based on what I read http://www.blueclaw-db.com/docmd_close_example.htm : If you leave the objecttype and objectname arguments blank (the default constant, acDefault, is assumed for objecttype), Microsoft Access closes the active window
Any help would be greatly appreciated. Thank you.
You don't need code DoCmd.Close acQuery, "Import", acSaveNo at all. This command tries to close a query "Import", but you didn't open this query. You opened a recordset, based on this query and you closed the recordset correctly.
If you need to close the form with name "Import", use
DoCmd.Close acForm, "Import", acSaveNo
If you are looking to close Access completely, use:
Application.Quit
Your line of code DoCmd.Close acQuery, "Import", acSaveNo is not necessary as you are opening a recordset, not the query. rst.close and set rst = nothing is sufficient for memory management.
On a side note, I would recommend including an if statement for stepping through your recordset. If the recordset is blank, you will receive an error if left unchecked. Try inserting your for loop inside this if statement:
If not rst.eof and not rst.bof then
'for loop...
end if
Related
I have an MS Access database with a set of forms to enter vegetation data for a large monitoring project. I have one form called frmTransect with a button that opens a second form called frmLPI which is set up as an unbound main form with a subform called frmLPIDetail bound to a sql server database table. The main form has just two unbound fields, DataObs and DataRec, both of which are comboboxes. These two field are set up with an AfterUpdate event procedure to populate their corresponding fields in the subform, Data_observer and Data_recorder. This works perfectly. I wanted to have the unbound fields autopopulate with the last value in the subform of Data_observer and Data_recorder when the form is lauched again. To do this I used a FormOpen event procedure. Below is the code:
Private Sub Form_Open(Cancel As Integer)
Me.TransectOID = Me.OpenArgs
Dim rs As DAO.Recordset
Set rs = Me!frmLPIDetail.Form.RecordsetClone
If rs.RecordCount > 0 Then
If Not rs.BOF Then
rs.MoveLast
rs.MovePrevious
End If
If Not IsNull(rs!Data_recorder.Value) Then
Me.DataRec.Value = rs!Data_recorder.Value
Me.frmLPIDetail.Form.Data_recorder.DefaultValue = """" & Me.DataRec.Value & """"
End If
If Not IsNull(rs!Data_observer.Value) Then
Me.DataObs.Value = rs!Data_observer.Value
Me.frmLPIDetail.Form.Data_observer.DefaultValue = """" & Me.DataObs.Value & """"
End If
rs.MoveLast
rs.MoveFirst
While Not rs.EOF
rs.Edit
rs!Data_recorder.Value = Me.DataRec.Value
rs!Data_observer.Value = Me.DataObs.Value
rs.Update
rs.MoveNext
Wend
End If
rs.Close
Set rs = Nothing
Me.Dirty = False
End Sub
Here is where things get weird. When I click the command button on frmTransect, frmLPI opens, but the FormOpen event procedure above doesn't get launched. However, if I switch into design view, and then back into Form View, it does trigger, and works as intended! How can I get this event procedure to launch when I open the frmLPI using the command button in frmTransect? Any help would be much appreciated.
And it turned out it was as simple as adding a Me.Refresh and Me.Requery to my code block:
Private Sub Form_Open(Cancel As Integer)
Me.TransectOID = Me.OpenArgs
Me.Refresh
Me.Requery
Dim rs As DAO.Recordset
Set rs = Me!frmLPIDetail.Form.RecordsetClone
If rs.RecordCount > 0 Then
rs.MoveLast
rs.MovePrevious
If Not IsNull(rs!Data_recorder.Value) Then
Me.DataRec.Value = rs!Data_recorder.Value
Me.frmLPIDetail.Form.Data_recorder.DefaultValue = """" & Me.DataRec.Value & """"
End If
If Not IsNull(rs!Data_observer.Value) Then
Me.DataObs.Value = rs!Data_observer.Value
Me.frmLPIDetail.Form.Data_observer.DefaultValue = """" & Me.DataObs.Value & """"
End If
rs.MoveLast
rs.MoveFirst
End If
rs.Close
Set rs = Nothing
Me.Dirty = False
End Sub
I have a fixed with txt file that I am trying to parse based on data in a certain position.
I need to loop through the recordsets an have it append into a table.
I am having a problem trying to parse out the initial txt file.
I am using where Mid("AllData", 1, 2) = "BR"
I have the code below. What am I doing wrong?
Sub BR_Records()
On Error GoTo ErrorHandler
Dim strSQL As String
Dim rs As DAO.Recordset
strSQL = "TBL_AllData"
Set rs = CurrentDb.OpenRecordset(strSQL)
With rs
If Not .BOF And Not .EOF Then
.MoveLast
.MoveFirst
While (Not .EOF)
Debug.Print rs.Fields("AllData"); where.Mid("AllData", 1, 2) = "BR"
.MoveNext
Wend
End If
.Close
End With
ExitSub:
Set rs = Nothing
Exit Sub
ErrorHandler:
Resume ExitSub
End Sub
Try this:
With rs
If .RecordCount > 0 Then
.MoveFirst
While Not .EOF
If Mid(.Fields("AllData").Value, 1, 2) = "BR" Then
Debug.Print .Fields("AllData").Value
End If
.MoveNext
Wend
End If
.Close
End With
In access 2013, I'm using a form (called "Table1") linked to a table that has an attachment field that I'm adding a scanned document (bmp) to. There are two textboxes that I use to name the scanned document on the form. Everything works if I input the record then hit save and then click my button (called testButton), but if I don't hit save, the attachment saves to the last record or a few records back. I'm pretty sure it's a saving issue, because when I try to scan and attach after the computer has been dormant, it works just fine, I'm guessing autosave. However, if I'm trying to scan multiple records back to back, the attachment goes to the previous record if I don't hit save on the ribbon. I've tried placing
DoCmd.Save acForm, "Table1"
or
If Me.Dirty Then
Me.Dirty = False
MsgBox ("File Saved")
End If
or even
DoCmd.RunCommand acCmdSaveRecord
at different points in the code to no avail. The DoCmd functions save the record, but start the recordset at the first record, not the one I'm currently inputting. So instead of attaching to the second to last record, it attaches to the first record.
My goal is to be able to hit the button and it work perfectly without having to hit save. I even looked for a code that does exactly what the save button on the ribbon does to no avail.
Here is the current code I'm using.
Option Compare Database
Dim FileLocation As String
Dim diagFile As FileDialog
Private Sub testButton_Click()
'DoCmd.Save acForm, "Table1" (Commented out, because it's not working)
Dim db As DAO.Database
Dim rsParent As DAO.Recordset2
Dim rsChild As DAO.Recordset2
If Me.Dirty Then
Me.Dirty = False
MsgBox ("File Saved")
End If
Me.testBox = Me.Payment & Me.Merchant ' I use this to see the input on screen
ScanImage
AttachImage
End Sub
Private Sub ScanImage()
'This method works, it's the AttachImage that's causing issues.
Set diagFile = Application.FileDialog(msoFileDialogSaveAs)
diagFile.Title = "Save Bitmap File As..."
diagFile.InitialFileName = Me.Payment & " " & Me.Merchant & ".bmp"
diagFile.Show
FileLocation = diagFile.SelectedItems(1)
Dim scanDiag As New WIA.CommonDialog
Dim image As WIA.ImageFile
Set image = scanDiag.ShowAcquireImage(ScannerDeviceType)
image.SaveFile FileLocation
MsgBox ("File Saved")
' MsgBox (CurrentRecord) I used this to see on screen the record I'm inputing
End Sub
Private Sub AttachImage()
MsgBox ("Step 1 attaching") ' I use this and all the MsgBoxes to see where in the code the procedure is.
'MsgBox ("Step 2 attaching")
On Error GoTo Err_AddImage
Set db = CurrentDb
Set rsParent = Me.Recordset
rsParent.Edit
Set rsChild = rsParent.Fields("Receipt").Value
'MsgBox "Nombre el archivo: " & rsChild("FileName").Value
'MsgBox "Tipo de archivo: " & rsChild.Fields("FileType").Value
'MsgBox "Data del archivo: " & rsChild.Fields("FileData").Value
'Do Until rsChild.EOF
' For Each fld In rsChild.Fields
' Debug.Print fld
' Next fld
' rsChild.MoveNext
' Loop
'MsgBox ("Step 3 attaching")
rsChild.AddNew
rsChild.Fields("FileData").LoadFromFile ("C:\Users\omoawotona\Desktop\Receipt Clone\" & Me.Payment & " " & Me.Merchant & ".bmp")
rsChild.Update
rsParent.Update
'MsgBox ("Step 4 attaching")
Me.Refresh
'MsgBox ("Step 5 attaching")
'MsgBox ("Attachment done")
Exit_AddImage:
Set rsChild = Nothing
Set rsParent = Nothing
Exit Sub
Err_AddImage:
If Err = 3820 Then
MsgBox ("File already part of the multi-valued field!")
Me.Refresh
Resume Next
Else
MsgBox "Some Other Error occured!", Err.Number, Err.Description
Resume Exit_AddImage
End If
End Sub
I'm using a cmd button to open a popup (single) form that has (2) txtboxes that I want to reflect the information from a single record in the previous (continuous) form. The cmd will
Code on the cmd button:
Private Sub cmdReassign_Click()
On Error GoTo ErrHandler
Dim strOpenArgs As String
strOpenArgs = Me.txtToolGroupID & "," & Me.txtEmployee_Name
DoCmd.OpenForm "popfrmReassignGroupedTools", OpenArgs:=strOpenArgs '
ExitHere:
Exit Sub
ErrHandler:
MsgBox Err.Number & ": " & Err.Description, vbExclamation
Resume ExitHere
End Sub
Code on Form_Open
Private Sub Form_Open(Cancel As Integer)
On Error GoTo ErrHandler
Dim dbs As DAO.Database
Dim rst As DAO.Recordset
Dim strSQL As String
Dim strOpenArgs As String
strOpenArgs = Me.OpenArgs
Set dbs = CurrentDb
strSQL = "SELECT * From qryToolReassignment_Grouped Where ToolGroupID=" & Me.txtToolGroupID & ";"
Set rst = dbs.OpenRecordset(strSQL)
If rst.EOF Then
GoTo ExitHere
End If
With Me
.txtToolCategoryQty = rst.Fields("[Quantity]")
.txtToolLocation = rst.Fields("[Employee Name]")
End With
ExitHere:
On Error Resume Next
Set rst = Nothing
Set dbs = Nothing
Exit Sub
ErrHandler:
MsgBox Err.Number & ": " & Err.Description, vbExclamation
Resume ExitHere
End Sub
I'll admit I borrowed the code from a similar setup where the information was called from a cbo not a cmd. When the popup form opens, only the first record in the query is shown not the record associated to the cmd. Any suggestions. TIA.
Not clear to me what you want. If popup form is BOUND and you want it to open to existing record then use the WHERE argument of OpenForm:
DoCmd.OpenForm "popfrmReassignGroupedTools", , , "ToolGroupID=" & Me.txtToolGroupID
If txtToolGroupID is on the continuous form then the popup form Open event cannot reference it with Me alias.
If you want to pass multiple values with OpenArgs, will have to use string manipulation functions to parse the data elements.
If Not IsNull(Me.OpenArgs) Then
intID = Left(Me.OpenArgs, InStr(Me.OpenArgs, ",")-1)
strEmp = Mid(Me.OpenArgs, InStr(Me.OpenArgs, ",")+1)
End If
Instead of all that code to declare and open recordset object, a DLookup() might serve.
I am experiencing a problem with vb in access. There is main form (say it parentForm), which has two buttons that trigger two different forms (say it childForm1 and childForm2). Both child forms perform checks on their Load events. If a condition fails, the childForm has to close. The problem is that in childForm1, the code works properly, in the childForm2 something goes completely wrong.
It seems that the close event is totally ignored. After the onLoad event, the process is carried out to the onCurrent event, which shouldn't happen! Below is the code of the onLoad event of childForm2.
Private Sub Form_Load()
On Error Resume Next
Dim db As Database
Dim rst As Recordset
Dim stDocName As String
stDocName = "childForm2"
closeEvent = False
Set db = CurrentDb
If a<> 0 And b<> 0 Then
Set rst = db.OpenRecordset("SELECT * FROM tbl1 WHERE Cust Like '*" & a & "*' AND Cust2 Like '*" & b & "*';")
If (rst.EOF Or rst.BOF) And IsLoaded(stDocName) Then
MsgBox ("No record found!")
rst.Close
SetWarnings = True
closeEvent = True
Me.SetFocus
DoCmd.Close acForm, stDocName, acSaveNo
End If
ElseIf a = 0 And b <> 0 Then
Set rst = db.OpenRecordset("SELECT * FROM tbl1 WHERE Cust2 Like '*" & b & "*';")
If (rst.EOF Or rst.BOF) Then
MsgBox ("No record found!")
rst.Close
DoCmd.Close acForm, stDocName
End If
End If
db.Close
End Sub
Also, I tried to use a global boolean variable (closeEvent in code), which is initialized to False and gets True, when the form must close. This variable is checked in the onCurrent event in order to close the form. However, when i debugged the code, the variable seems to lose its (True) value when passing from onLoad to OnCurrent event!
Any suggestion is more than appreciated.
Thanks in advance,
Maria
Use the Form_Open event instead of the Form_Loadevent.
Then, instead of closing the form (=Docmd.Close) use the built in Cancel argument to cancel the form's opening.
Private Sub Form_Open(Cancel As Integer)
If **condition not met** then
Cancel = True 'this stops the form from opening
End If
End Sub