I made a simple userform to insert certain text based on whether certain clickboxes are checked. Shortened version below. Problem is that, as my code is currently written, if cbx1 isn't clicked but cbx2 is, then the string that gets pasted in leads with a new line. Is there a simple way to just add at the end something like "If [first line of strNewText] = vbNewLine[?] Then [delete first line of strNewText]"? A better solution? Thanks!
Private Sub cmdInsert_Click()
Application.ScreenUpdating = False
Dim strToAdd As String
Dim text1 As String
Dim text2 As String
Dim text2 As String
text1 = "This is Text 1."
text2 = "This is Text 2."
text3 = "This is Text 3."
If cbx1 = True Then strToAdd = text1
If cbx2 = True Then strToAdd = strToAdd & vbNewLine & text2
If cbx3 = True Then strToAdd = strToAdd & vbNewLine & text3
With ActiveDocument
Selection.Text = strToAdd
Selection.Collapse
End With
Application.ScreenUpdating = True
End Sub
CodePudding user response:
You can use the Iif
function to test whether strToAdd
contains any text before adding a new line.
Private Sub cmdInsert_Click()
Application.ScreenUpdating = False
Dim strToAdd As String
Dim text1 As String
Dim text2 As String
Dim text3 As String
text1 = "This is Text 1."
text2 = "This is Text 2."
text3 = "This is Text 3."
If cbx1 = True Then strToAdd = text1
If cbx2 = True Then strToAdd = strToAdd & IIf(strToAdd = vbNullString, "", vbNewLine) & text2
If cbx3 = True Then strToAdd = strToAdd & IIf(strToAdd = vbNullString, "", vbNewLine) & text3
With ActiveDocument
Selection.Text = strToAdd
Selection.Collapse
End With
Application.ScreenUpdating = True
End Sub
CodePudding user response:
I would flip the logic a little bit and add the vbNewLine on the end. This way, no matter the combination of checkmarks I know the string always ends with a vbNewLine. Then it is a simple matter to remove the trailing vbNewLine. This approach also keeps the code a little more concise:
If cbx1 = True Then strToAdd = strToAdd & text1 & vbNewLine
If cbx2 = True Then strToAdd = strToAdd & text2 & vbNewLine
If cbx3 = True Then strToAdd = strToAdd & text3 & vbNewLine
If Len(strToAdd) > 0 Then strToAdd = Mid(strToAdd, 1, Len(strToAdd) - 2)