Applying vbCrLf to the content of a textbox - vba

I've got a userform within an Excel vba project. At design-time it is empty.
In the form initialize event I've got the following code:
Private Sub UserForm_Initialize()
txtSQL.value = _
"SELECT MyName = ""ColY"" " & vbCrLf & _
"FROM SomeTable " & vbCrLf & _
"GROUP BY Customer " & vbCrLf & _
"ORDER BY Customer DESC"
End Sub
I was hoping for 4 separate lines of text in the textbox but instead have the following:
Am I using the wrong control? Or am I using the right control in the wrong way?

Whoops: maybe I should go to bed...
At design-time set multi-line property to True!

Related

Word in message box appears in a different line

I use the following VBA to open a message box:
Sub Message()
MsgBox ("Do you want create a file on your desktop?" _
& vbCr & " " _
& vbCr & "Once you click yes an unprotected file with all sheets visible will be saved on your desktop and opened. You can immediately start working with this file.")
End Sub
All this works fine.
However, as you can see in the screenshot the word "file" goes in a different line. Is it possible to format the messagebox or change the VBA code so the word "file" does not appear in a different line?
It depends on the resolution of the PC of the user. In my case I even get it like this:
If you want to control the lines, then you should write a custom form. There you would have much better control over the display, and if you play a bit with its properties, you would mimic exactly the MsgBox():
Some sample code, Label1 is a label element:
Private Sub UserForm_Initialize()
Me.Label1 = "Do you want create a file on your desktop?" _
& vbCr & " " _
& vbCr & "Once you click yes an unprotected file with all sheets visible will be saved on your desktop and opened." & _
vbCrLf & "You can immediately start working with this file."
End Sub
Perhaps adjust your code with line breaks to suit. For example:
Sub Message()
MsgBox ("Do you want create a file on your desktop?" _
& vbCr & " " _
& vbCr & "Once you click yes an unprotected file" _
& vbCr & " " _
& vbCr & "with all sheets visible will be saved on your desktop and opened." _
& vbCr & " " _
& vbCr & "You can immediately start working with this file.")
End Sub

How to create a comment box with time and date stamp in Access using VBA

Completely new to VBA and need help with detailed instructions (dummy version for me).
I have a table with various columns and the following columns, specifically:
ReviewerComments
NewComment
I created a form with both of these fields and need to create an Append Comment button that moves the text from NewComment field and appends it to ReviewerComment field and time/date stamps the comments as they are added. I named this button cmdAppendComment.
I had seen someone else post something and I tried, but as I am completely new to this I know I messed it up. Any help is greatly appreciated.
This is what the VBA code looks like right now:
Private Sub cmdAppendComment_Click()
If (IsNull(NewComment.Value)) Then
MsgBox ("Please provide a comment before clicking" & _
"on the Append Comment button.")
Exit Sub
End If
If (IsNull(ReviewerComments.Value)) Then
ReviewerComments.Value = NewComment.Value & " ~ " & _
VBA.DateTime.Date & " ~ " & VBA.DateTime.Time
Else
ReviewerComments.Value = ReviewerComments.Value & _
vbNewLine & vbNewLine & _
NewComment.Value & " ~ " & _
VBA.DateTime.Date & " ~ " & VBA.DateTime.Time
End If
NewComment.Value = ""
End Sub
I have some suggestions for your code:
1. Do not check if a textbox is null but how many characters your textbox has. You should always do it that way because otherwise you tend to get errors.
If (len(Me.NewComment.Value & "") > 0) Then
MsgBox ("Please provide a comment before clicking" & _
"on the Append Comment button.")
Exit Sub
End If
Here you check the length of the string in your textbox. You need to append "" because otherwise you tend to get null-errors or something similar.
2. You forgot to reference the objects in your form correctly. You have your form and in that form you put your textboxes and also your VBA-code. Your can reference all your objects with "Me.[FormObjects]".
The compiler complains that "NewComment.Value" or "ReviewerComment.Value" is not initialized or in other words not dimensioned. With correct reference this should stop.
Private Sub cmdAppendComment_Click()
If (len(Me.NewComment.Value & "") > 0) Then
MsgBox ("Please provide a comment before clicking" & _
"on the Append Comment button.")
Exit Sub
End If
If (IsNull(Me.ReviewerComments.Value)) Then
Me.ReviewerComments.Value = Me.NewComment.Value & " ~ " & _
VBA.DateTime.Date & " ~ " & VBA.DateTime.Time
Else
Me.ReviewerComments.Value = Me.ReviewerComments.Value & _
vbNewLine & vbNewLine & _
Me.NewComment.Value & " ~ " & _
VBA.DateTime.Date & " ~ " & VBA.DateTime.Time
End If
Me.NewComment.Value = ""
End Sub

MS Access Nested Subform reference error

I'm having trouble referencing a subform within a subform on a form.
Private Sub Command37_Click()
Dim UMsge As String
Me.Filter = "ID=" & Me.ID
Me.FilterOn = True
UMsge = "Swimmer's Name: " & Forms![Parents]![Swimmers Subform].Form![Memb First Name] & " " & Forms![Parents]![Swimmers Subform].Form![Memb Last Name] & vbCrLf & vbCrLf & "Roster Group: " & Forms![Parents]![Swimmers Subform].Form![Roster Group] & vbCrLf & vbCrLf & "Monthly Fee: " & Format(Forms![Parents]![Swimmers Subform].Form![Parents - Payment subform].Form![GroupMonthlyPrice], "Currency") & vbCrLf & vbCrLf & "Thank You!"
DoCmd.SendObject acSendForm, "Parents", acFormatPDF, Me.Email, , , "Monthly Fees Owed As Of " & DateSerial(Year(Date), Month(Date), Day(Date)), UMsge, True
End Sub
It's only this last piece:
Format(Forms![Parents]![Swimmers Subform].Form![Parents - Payment subform].Form![GroupMonthlyPrice], "Currency")
FormView:
First, it looks like you using a sub datasheet. They are somewhat different then sub forms (in that you cannot name them, they are named automatic for you).
Further, since your button is in the same form, for the top most form, we can use β€œme” keyword. This will simple your code quite a bit.
Assuming we had 3 nested sub forms, we could use this syntax:
strName = Me.Swimmers_SubForm.Form![memb First Name] & " " & _
Me.Swimmers_SubForm.Form![memb Last Name]
The above will get you the name in the first nested sub form.
However, you next sub form looks VERY much like a Subdatasheet.
Two things:
If this is a sub data sheet (as opposed to sub form, then if this form has never been expanded, then the reference will break (the child form does not exist). This is often the same for if the sub datasheet has no child records.
So you need (should) to trap this error.
Also, if this is a sub data sheet, then you cannot give the sub form control a name – it starts at child0 and that likely is your issue.
Note that the record return will be the highlighted row, and in your example screen shot, I see two rows, and I DO NOT see the column called [GroupMonthlyPrice]. However I will assume that this is the column you wish to reference? Or is do you want the column called [Monthly Fee] ?
So to reference that 3rd nested form, the syntax would be this:
Me.Swimmers_SubForm.Form!Child0.Form![GroupMonthlyPrice]
So to break all this down, I would use this code:
Dim f As Form ' ref to sub form
Dim UMsge As String
Set f = Me.Swimmers_Subform.Form
UMsge = "Swimmer's Name: " & f![Memb First Name] & " " & f![Memb Last Name] & vbCrLf & _
"Roster Group: " & f![Roster Group] & vbCrLf & vbCrLf & _
"Monthly Fee: " & Format(f!Child0.Form![GroupMontlyPrice], "Currency")
The referenced "f" in above is not required, but certainly makes code much more readable.
Note that you might have to replace child0 with the name of the sub form control, but as I stated, this looks like a sub datasheet, and quite sure the first sub datasheet is called Child0.

RecordSource in Access SQL

I have a form which allows the user to view all records with the LinkRef field equal to a specified value and also either the Clearance Applying For or Clearance Level a certain value.
LinkRef is a user ID which is pulled in using OpenArgs from the previous form. The code for the form_load I have presently is:
Private Sub Form_Load()
'MsgBox Me.OpenArgs
Me.C_LinKRef = Me.OpenArgs
Me.chbToggleEdit.Value = False
'MsgBox Me.C_LinKRef
Dim mySQL As String
mySQL = _
"Select * " & _
"From TabClearDetail " & _
"Where (C_LinKRef = " & Me.C_LinKRef & ") " & _
"And ([Clearance Applying For] = 'BPSS' " & _
"Or [Clearance Applying For] = 'BPSS (EDF)' " & _
"Or [Clearance Applying For] = 'BPSS (Magn)' " & _
"Or [Clearance Applying For] = 'BPSS (Sella)' " & _
"Or [Clearance Applying For] = 'BPSS Equiv' " & _
"Or C_ClearanceLevel = 'BPSS' " & _
"Or C_ClearanceLevel = 'BPSS (EDF)' " & _
"Or C_ClearanceLevel = 'BPSS (Magn)' " & _
"Or C_ClearanceLevel = 'BPSS (Sella)' " & _
"Or C_ClearanceLevel = 'BPSS Equiv' " & _
"Or C_ClearanceLevel = 'DESTROYED' " & _
"Or C_ClearanceLevel = 'Lapsed' " & _
"Or C_ClearanceLevel = 'NOT_FLWDUP' " & _
"Or C_ClearanceLevel = 'NOT_SPECIFIED' " & _
"Or C_ClearanceLevel = 'Refused' " & _
"Or C_ClearanceLevel = 'Withdrawn');"
Me.RecordSource = mySQL
'MsgBox Me.RecordsetClone.RecordCount
End Sub
mySQL seems to behave as it should when there are matching records. But sometimes there won't be any records because the specified person doesn't have any of these clearance levels and hasn't applied for them, then I would like the form to come up blank or a message to appear saying that there is no matching records.
Presently though if there is no matching records the form will pull in the LinkRef but fill all the other text boxes with values from a completely different record (it seems to be the last record I viewed). Not to sure how to remedy this, I tried to use the RecordsetClone.RecordCount to say if it is equal to 0 then msgbox, but it seems to late to do that as it always seems to find at least 1 entry, as even if there should be 0 it has already populated the textboxes with data from another field so 1 is found.
The LinkRef textbox is populated from OpenArgs. All other textboxes are populated using a query which looks in the TabClearDetail table and pulls the values in. I'm starting to think I'd be better either just using Queries or just using Code, but I wasn't sure how to use OpenArgs in a query and for some things it's so much quicker to make a query than code.
Here is the code for my save dialog I refer to in reply to #Roland post. This code is called in the Form_Close() sub.
Private Sub SaveDialog()
Dim Msg, Style, Title As String
Dim Response As Integer
Msg = "Would you like to save your changes?"
Style = vbYesNoCancel
Title = "Save Changes"
On Error GoTo Err_BackFromAddBPSSButton_Click
Response = MsgBox(Msg, Style, Title)
If Response = vbYes Then
'DoCmd.Close
DoCmd.OpenForm ("Basic Personal Information")
Else
If Response = vbNo Then
Me.Undo
'DoCmd.Close
DoCmd.OpenForm ("Basic Personal Information")
End If
End If
Exit_BackFromAddBPSSButton_Click:
Exit Sub
Err_BackFromAddBPSSButton_Click:
MsgBox Err.Description
Resume Exit_BackFromAddBPSSButton_Click
End Sub
Apologies for the very wordy question, hopefully all the detail is necessary and it makes sense, any suggestions HUGELY appreciated!
Try changing the order of events:
Don't set the TextBox value first. Pass the OpenArgs to the mySql string. With mySql open a recordset in VBA (OpenRecordset) and do a RecordCount. If it is zero then set the Recordsource to SELECT * FROM TabClearDetail WHERE 1=2 . Else set mySQl as the Recordsource (or pass the Recordset). Only then set the TextBox and CheckBox.
Private Sub Form_Load()
Dim i as Integer
i = Me.OpenArgs
Dim mySQL As String
mySQL = _
"Select * " & _
"From TabClearDetail " & _
"Where (C_LinKRef = " & Me.C_LinKRef & ") " & _
"And ([Clearance Applying For] IN ('BPSS','BPSS (EDF)','BPSS (Magn)','BPSS Sella)','BPSS Equiv') " & _
"Or C_ClearanceLevel IN ('BPSS','BPSS (EDF)','BPSS (Magn)','BPSS (Sella)','BPSS Equiv','DESTROYED','Lapsed','NOT_FLWDUP','NOT_SPECIFIED','Refused','Withdrawn'));"
Dim rst as Recordset
Set rst = CurrentDB.OpenRecordset(mySQL)
rst.MoveLast
rst.MoveFirst
If rst.RecordCount = 0 then
Me.RecordSource = "SELECT * FROM TabClearDetail WHERE 1=2"
Me.C_LinKRef = ""
Me.chbToggleEdit.Value = False
Else
Me.RecordSource = mySQL
Me.C_LinKRef = i
Me.chbToggleEdit.Value = False
End If
rst.Close
Set rst = Nothing
End Sub
Sorry, cannot test it here so may be a little buggy. If any problems I will check tomorrow
Using a query and passing [Forms]![BPSS Clearance].[OpenArgs] into that as well as the conditions on C_ClearanceLevel and Clearance Applying For has worked for me. No idea why the code didn't work because in theory it's doing the same thing, but I've got a solution so I'm happy. Thanks for all the suggestions

Update Button not updating

I have been hammering out the issues of this form for about a week now and have almost come to a solution, but I have hit a brick wall. I have a large form with multiple functions, one of the functions is to edit a subform that houses a list of codes and other various pieces of data. When I click the edit button it auto fills the boxes with the selected data. The function works when I click the update button but when I click the save button it does not actually save the data. The code is:
Private Sub cmdEdit_Click()
'check whether there exists data in list
If Not (Me.TableSub.Form.Recordset.EOF And Me.TableSub.Form.Recordset.BOF) Then
'Get data to text box control
With Me.TableSub.Form.Recordset
Me.text_key = .Fields("KW")
Me.txt_code = .Fields("Code")
Me.combo_source = .Fields("Source")
'Store id of student in tag of text id in case id is modified
Me.txt_code.Tag = .Fields("Code")
'Change caption of button add to Update
Me.cmdAdd.Caption = "Update"
'disable button edit
Me.cmdEdit.Enabled = False
End With
End If
End Sub
This is the code for the save or Add button.
Private Sub cmdAdd_Click()
'when we click on button Add there are two options
'1. For insert
'2. For Update
If Me.txt_code.Tag & "" = "" Then
'this is for insert new
'add data to table
CurrentDb.Execute "INSERT INTO KWTable(KW, Source, Code) " & _
" VALUES('" & Me.text_key & "','" & Me.combo_source & "','" & _
Me.txt_code & "')"
Else
'otherwise (Tag of txtID store the id of student to be modified)
CurrentDb.Execute "UPDATE KWTable " & _
" SET KW='" & Me.text_key & "'" & _
", Code='" & Me.txt_code & "'" & _
", Source='" & Me.combo_source & "'" & _
" WHERE KW='" & Me.text_key & "'"
End If
'clear form
cmdClear_Click
'refresh data in list on form
TableSub.Form.Requery
End Sub
You're only copying values to the fields. They're not bound to the subform's recordset in any way. So, to save them, just reverse the process:
With Me.TableSub.Form.Recordset
.Edit
.Fields("KW") = Me.text_key
.Fields("Code") = Me.txt_code
.Fields("Source") = Me.combo_source
.Fields("Code") = Me.txt_code.Tag
.Update
End With
It sounds to me like you are looking at forcing the current bound form's data to save.
If Me.Dirty Then Me.Dirty = False
This statement essentially says "If there is unsaved data on this form/report - save it"
You can also reference your subform
If subform.Form.Dirty Then subform.Form.Dirty = False
It will do the same thing as Fabio's suggestion but I find it a bit more reliable with bound forms than the recordset approach.