I wanted to insert some texts(new line) in between existing texts in a textbox (multiline = true).
Example: (Textbox1.text's value is written below)
Name: Name of Client
DOB: 11/11/11
>>>THIS IS WHERE I WHAT TO INSERT THE VALUE OF TEXTBOX2.TEXT
Hospitalization: No
Serial Number: 12345678
Private Sub cmdTransfer_Click()
Dim SearchNote As Integer, SearchThis As String, tx2 As String
If cb9.Value = True Then
tx2 = "ADDRESS: " & vbTab & text2.Text & vbCrLf
End If
SearchThis = "Hospitalization"
SearchNote = InStr(Textbox1.Text, SearchThis)
If SearchNote Then
With textbox1
.SetFocus
.SelStart = SearchNote
.Text = .Text & .SelStart & tx2
End with
End If
End Sub
What I'm doing in my code is I'm getting the number of characters before the "Hospitalization" so that I can insert the value of Textbox2 before it. I dont know how to do that tho. Please help.
Thanks!
I believe the code you are looking for is this:
Left(SearchNote, InStr(1, SearchNote, "Hospitalization") - 1) & "new text to insert" & Mid(SearchNote, InStr(1, SearchNote, "Hospitalization"))
Left will take the first few letters up to the starting point of "Hospitalization". Then you insert the new string (possible with a new line before and after with & chr(10) &). Then you add with Mid everything after "Hospitalization".
Since I don't have a sample copy of your spreadsheet, there is a chance that one/some of my variables might be different. If you find problems with any of these, check all of the vars.
Solution #1: Create module and add this function:
Function addText(txtBox As String, addString As String)
Dim endIndex As Long
Dim SearchThis As String
Dim input1, input2, input3 As String
SearchThis = "Hospitalization"
' Get index of Hospitalization
endIndex = InStr(1, txtBox, SearchThis) - 1
If endIndex > 0 Then
input1 = Mid(txtBox, 1, endIndex)
input2 = addString & vbNewLine
input3 = Mid(txtBox, endIndex, Len(txtBox))
' Return with added text
addText = CStr(input1 & input2 & input3)
End If
End Function
then call in your button to update your text box:
Private Sub cmdTransfer_Click()
Dim tx2 As String
If cb9.Value = True Then
tx2 = "ADDRESS: " & vbTab & text2.Text & vbNewLine
Else
' Stop if there is nothing to add
End
End If
If textbox1.Value <> vbNullString Then
textbox1.Value = addText(textbox1.Value, tx2)
End If
End Sub
Solution #2: Call everything from within your button:
Private Sub cmdTransfer_Click()
Dim endIndex As Long
Dim SearchThis As String
Dim input1, input2, input3 As String
Dim txtBox As String, tx2 As String
'set tx2
If cb9.Value = True Then
tx2 = "ADDRESS: " & vbTab & text2.Text & vbNewLine
Else
' Stop if nothing to add
End
End If
If textbox1.Value <> vbNullString Then
' set txtBox variable
txtBox = textbox1.Value
Else
' Avoid Error if text box is null
End
End If
SearchThis = "Hospitalization"
' Get index of Hospitalization
endIndex = InStr(1, txtBox, SearchThis) - 1
If endIndex > 0 Then
input1 = Mid(txtBox, 1, endIndex)
input2 = tx2 & vbNewLine
input3 = Mid(txtBox, endIndex, Len(txtBox))
textbox1.Value = input1 & input2 & input3
End If
End Sub
What i would do is split text1 into an array then just add the text in the middle, mainString is text1, midStr is text2:
Dim mainStr as String, midStr as String, ArreStr() as String
mainStr=text1.text:midStr=text2.text
ArreStr=Split(mainStr,VBNewLine)
text1.text=ArreStr(0) & vbnewline & midStr & vbnewline & ArreStr(1)
Related
I try to many times but failed to get rid of runtime error 13. It shows error in me.filter line. Help will be appreciated
private Sub Form_Open(Cancel As Integer)
Dim arg() As Variant
If Nz(Me.OpenArgs) = 0 Then
Exit Sub
Else
MsgBox (Me.OpenArgs)
If Len(Me.OpenArgs) > 0 Then
arg = Split(Me.OpenArgs, "|")
Me.Filter = "[lab book]=' " & "arg(0)" & "" And "[starting Page]='" & arg(1) & "'"
Me.FilterOn = True
End If
End If
End Sub
Try this - and Page is numeric, I guess:
Private Sub Form_Open(Cancel As Integer)
Dim arg() As Variant
If Not IsNull(Me.OpenArgs) Then
MsgBox (Me.OpenArgs)
arg = Split(Me.OpenArgs, "|")
Me.Filter = "[lab book] = '" & arg(0) & "' And [starting Page] = " & arg(1) & ""
Me.FilterOn = True
End If
End Sub
Private Sub Form_Open(Cancel As Integer)
'an array can be assigned to a variant, but you cannot assign to an array
'Spit returns an array of strings
Dim Arg As Variant 'so make Arg a variant instead of an array of variants
Dim strsql As String 'combining sql strings is very error prone. When debugging print them
If Not IsNull(Me.OpenArgs) Then
'MsgBox (Me.OpenArgs)
Arg = Split(Me.OpenArgs, "|") 'So, now Arg holds the array of strings returned by split
strsql = "[lab book] = '" & Arg(0) & "' And [starting Page] = " & Arg(1)
Debug.Print strsql
'Based on my dummy data: [lab book] = 'science' And [starting Page] = 5
'It is important to wrap your text arguments in apostrophes when you combine them into the sql string or pass them already wrapped
'So check the datatypes in the table or query you are searching
Me.Filter = strsql
Me.FilterOn = True
End If
End Sub
I was hoping someone could help me work out why the the 'F' value in my code below continues to include my error label in the ErrorMessage String when the Count value is 5?
In the document, the content control contains text just like all the other controls (which work perfectly) but this content Control text value is not being recognised in the VBA code to map error labels.
Have tried just replacing the control and checking the properties match. Debug messages suggest the the value is just being set to the default Content Control Value of "Click or Tap here to input text".
Private Sub Create_Click()
Dim oCC As ContentControl
Dim oCC2 As ContentControl
Dim Mandatory(9) As String
Dim ErrorMessage As String
Dim ErrorCount As Integer
Dim ErrorLabel(9) As String
Dim objDoc As Document
Dim strFilename As String
Dim strFileString As String
Dim Number As String
Mandatory(0) = "A"
Mandatory(1) = "B"
Mandatory(2) = "C"
Mandatory(3) = "D"
Mandatory(4) = "E"
Mandatory(5) = "F"
Mandatory(6) = "G"
Mandatory(7) = "H"
Mandatory(8) = "I"
ErrorLabel(0) = "A Label"
ErrorLabel(1) = "B Label"
ErrorLabel(2) = "C Label"
ErrorLabel(3) = "D Label"
ErrorLabel(4) = "E Label"
ErrorLabel(5) = "F Label"
ErrorLabel(6) = "G Label"
ErrorLabel(7) = "H Label"
ErrorLabel(8) = "I Label"
ErrorMessage = ""
ErrorMessage = "The following mandatory fields are missing: "
For Count = 0 To 8
Set oCC = ActiveDocument.SelectContentControlsByTitle(Mandatory(Count)).Item(1)
MsgBox (oCC.Range.Text)
If Count = 0 Then
Number = ActiveDocument.SelectContentControlsByTitle(Mandatory(Count)).Item(1).Range.Text
End If
If oCC.Range.Text = "Click or tap here to enter text." Or oCC.Range.Text = "0.00" Then
ErrorMessage = ErrorMessage & vbCrLf & vbCrLf & "- " & ErrorLabel(Count)
MsgBox (oCC.Range.Text)
ErrorCount = ErrorCount + 1
End If
Next Count
If ErrorCount > 0 Then
MsgBox (ErrorMessage)
Else
strFileString = Number
MsgBox (strFileString)
strFilename = "Some Text Here" & " - " & strFileString & ".pdf"
With ActiveDocument
NewPath = .Path & "\" & strFilename
.SaveAs2 FileName:=NewPath, FileFormat:=wdFormatPDF
.ExportAsFixedFormat OutputFileName:=strFilename, ExportFormat:=wdExportFormatPDF, _
OpenAfterExport:=True, OptimizeFor:=wdExportOptimizeForPrint, _
Range:=wdExportAllDocument, Item:=wdExportDocumentContent
End With
End If
End Sub
Check there are no other content controls with the same title in the document.
I couldn't test your code for lack of data but from your description I guess that the ErrorMessage must be reset with each loop since it will be changed when used and would naturally retain the modified version thereafter.
Except for what follows the loop, I looked closely at your code in order to understand it. Perhaps, the changes I made will be of some use to you.
Option Explicit
Private Sub Create_Click()
Dim Doc As Document
Dim Mandatory() As String
Dim ErrorMessage As String
Dim ErrorCount As Integer
Dim strFilename As String
Dim strFileString As String ' this appears identical with 'Number'
Dim Number As String
Dim Count As Integer ' loop counter
Set Doc = ActiveDocument
Mandatory = Split("A B C D E F G H I")
Number = Doc.SelectContentControlsByTitle(Mandatory(0))(1).Range.Text
For Count = 1 To UBound(Mandatory) + 1
ErrorMessage = "The following mandatory fields are missing: "
With Doc.SelectContentControlsByTitle(Mandatory(Count))(1).Range
MsgBox "Number = " & Number & vbCr & .Text
If .Text = "Click or tap here to enter text." Or _
.Text = "0.00" Then
ErrorMessage = ErrorMessage & vbCrLf & vbCrLf & "- " & Mandatory(Count) & " Label"
MsgBox (.Text)
ErrorCount = ErrorCount + 1
End If
End With
If Count = 1 Then Exit For
Next Count
If ErrorCount > 0 Then
MsgBox (ErrorMessage)
Else
strFileString = Number
MsgBox (strFileString)
strFilename = "Some Text Here" & " - " & strFileString & ".pdf"
With Doc
NewPath = .Path & "\" & strFilename
.SaveAs2 FileName:=NewPath, FileFormat:=wdFormatPDF
.ExportAsFixedFormat OutputFileName:=strFilename, _
ExportFormat:=wdExportFormatPDF, _
OpenAfterExport:=True, _
OptimizeFor:=wdExportOptimizeForPrint, _
Range:=wdExportAllDocument, _
Item:=wdExportDocumentContent
End With
End If
End Sub
You can have VBA add the useful (some would say necessary) Option Explicit to all new code modules automatically. Select Tools > Options in the VBE window and check "Require Variable Declaration" on the Editor tab.
I am trying to get a specific cell value in brackets and check if this value is in other sheet. This is the column with the possible values:
StrS Format
HEADER
NOBREAK
IGNORE
REPEATABLE …-n can be up to 100
I want to split the string in the cell, check if its value is one of the above, if it is equal with "REPEATABLE" extract the following block specifications: . If is not defined in “BY Variables” show error. This is a similar issue with this one:
VBA-Count and collect every found match in regular expression -again have to get values with brackets
Here is my code:
Public Function IsItGood(aWord As Variant) As Boolean
Dim s As String
s = "|" '-means or
'tmp = s & aWord & s
tmp = Replace(s & aWord & s, ",", "")
patern = ""
patern = patern & "HEADER|NOBREAK|REPEATABLE" & s
If InStr(1, patern, tmp) > 0 Then
IsItGood = True
Else
IsItGood = False
End If
End Function
Function check_cell_values()
On Error Resume Next
Application.EnableEvents = False
Dim msg As String
msg = ""
Dim arr As Variant
Dim a As Variant
arr = Split(Target, " ")
For Each a In arr
If Target.Column = 10 And (Target.Row > 2 And Target.Row <= 308) Then
If IsItGood(a) Then
msg = msg & vbCrLf & (" In cell" + Target.Address(0, 0)) & vbCrLf & a & vbCrLf + "is ok"
Else
msg = msg & vbCrLf & (" In cell" + Target.Address(0, 0)) & vbCrLf & a & vbCrLf + "is invalid value"
Application.Undo
End If
End If
Next a
If msg <> "" Then MsgBox msg
check_cell_values = msg
End Function
Sub by_blocks_check()
Application.EnableEvents = False
Dim func1
func1 = check_cell_values()
End Sub
I think instead of a regular expression it is better to use an array from the possible values but I don`t know how to get the value after "Repeatable".
Example output:
I have a code that allows me to manually enter date in textbox1 which then gets selected in the calendar on the useform. There is a second textbox that allows me to add or subtract dates. The code works perfectly.
Userform Code -
Option Explicit
Private Sub TextBox1_Exit(ByVal Cancel As MSForms.ReturnBoolean)
If IsDate(Me.TextBox1.Value) Then Me.Calendar1.Value = Me.TextBox1.Value
End Sub
Private Sub TextBox2_Exit(ByVal Cancel As MSForms.ReturnBoolean)
Dim dt As Date
With Me
If IsDate(.TextBox1.Value) Then
dt = CDate(.TextBox1.Value) + Val(.TextBox2.Value)
.TextBox1.Value = dt
.Calendar1.Value = dt
End If
End With
End Sub
I would like to manually enter date in textbox1 in a specific format.
The formats will be -
dd
ddmmm
ddmmmyyy
I'm not sure how to write a code that does this.
The idea is to enter date in either of the 3 formats specified above in textbox1, which then gets selected on the calendar on the userform.
edited after op's clarification about allowed formats
you could build upon the following code
Option Explicit
Private Sub TextBox1_Exit(ByVal Cancel As MSForms.ReturnBoolean)
Dim txt As String, dayStr As String, monthStr As String, yearStr As String
Dim okTxt As Boolean
txt = Me.TextBox1.Value
Select Case Len(txt)
Case 2
dayStr = txt
okTxt = okDay(dayStr)
monthStr = month(Now)
yearStr = year(Now)
Case 5
dayStr = Mid(txt, 3, 3)
monthStr = Mid(txt, 3, 3)
okTxt = okDay(Left(txt, 2)) And okMonth(monthStr)
yearStr = year(Now)
Case 7
dayStr = Mid(txt, 3, 3)
monthStr = Mid(txt, 3, 3)
yearStr = Mid(txt, 6, 2)
okTxt = okDay(Left(txt, 2)) And okMonth(monthStr) And okYear(yearStr)
End Select
If Not okTxt Then
MsgBox "Invalid date" _
& vbCrLf & vbCrLf & "Date must be input in one of the following formats:" _
& vbCrLf & vbTab & "dd" _
& vbCrLf & vbTab & "ddmmm" _
& vbCrLf & vbTab & "ddmmmyy" _
& vbCrLf & vbCrLf & "Please try again", vbCritical
Cancel = True
Else
Me.Calendar1.Value = CDate(Left(txt, 2) & " " & monthStr & " " & yearStr)
End If
End Sub
Function okDay(txt As String) As Boolean
okDay = CInt(txt) > 0 And CInt(txt) < 31
End Function
Function okMonth(txt As String) As Boolean
Const months As String = "JANFEBMARAPRMAJJUNJULAUGSEPOCTNOVDEC"
okMonth = InStr(months, UCase(txt)) > 0
End Function
Function okYear(txt As String) As Boolean
okYear = CInt(txt) > 0 And CInt(txt) < 200 '<--| set your "limit" years
End Function
I want to display a textlog string in a userform's textbox.
Code might look like this:
Dim public textlog as string
sub button1_click()
' do some action
textlog = textlog & event_string & vbCrLf
'event_string might exceed more than 2 line
textlog = textlog & "button1 action" & vbCrLf
userform1.textbox1.text = textlog
end sub
sub button2_click()
' do some action
textlog = textlog & event_string & vbCrLf
'event_string might exceed more than 2 line
textlog = textlog & "button2 action" & vbCrLf
userform1.textbox1.text = textlog
end sub
However, the textbox should only contain 20 lines of information, while my
the contents of my textlog will exceed 20 lines.
How can I display only the latest (last) 20 lines of the textlog in textbox1?
You can use this function to return only the last N lines of a string, and then display that in your textbox.
Note that you have to specify what the line break character is. Depending on your specific application, it could be vbCrLf, vbCr, vbLf, or even some other delimiter.
Function GetLastLines(ByVal s As String, ByVal nLinesToDisplay As Long, _
Optional ByVal lineBreakChar As String = vbCrLf)
'Split the string into an array
Dim splitString() As String
splitString = Split(s, lineBreakChar)
'How many lines are there?
Dim nLines As Long
nLines = UBound(splitString) + 1
If nLines <= nLinesToDisplay Then
'No need to remove anything. Get out.
GetLastLines = s
Exit Function
End If
'Collect last N lines in a new array
Dim lastLines() As String
ReDim lastLines(0 To nLinesToDisplay - 1)
Dim i As Long
For i = 0 To UBound(lastLines)
lastLines(i) = splitString(i + nLines - nLinesToDisplay)
Next i
'Join the lines array into a single string
GetLastLines = Join(lastLines, lineBreakChar)
End Function
Example usage:
MsgBox GetLastLines( _
"line 1" & vbCrLf & "line 2" & vbCrLf & "line 3" & vbCrLf _
& "line 4" & vbCrLf & "line 5" & vbCrLf & "line 6", _
4, vbCrLf)
Only the last 4 lines are displayed:
Note that this assumes that your last line is not terminated by a line break. If it is, then you can tweak the code to deal with that.
Alternatively, you can use Excel's built-in SUBSTITUTE function, which is useful in this particular case, because it can locate a specific instance of a given character. So instead of building arrays you can use a one-liner:
Function GetLastLines2(ByVal s As String, ByVal nLinesToDisplay As Long, _
Optional ByVal lineBreakChar As String = vbCrLf)
'An arbitrary character that will never be in your input string:
Dim delim As String: delim = Chr(1)
'How many lines are there?
Dim nLines As Long
nLines = UBound(Split(s, lineBreakChar)) + 1
If nLines <= nLinesToDisplay Then
'No need to remove anything. Get out.
GetLastLines2 = s
Exit Function
End If
'Replace one line break with delim, split the string on it,
'return only second part:
GetLastLines2 = Split( _
WorksheetFunction.Substitute( _
s, lineBreakChar, delim, nLines - nLinesToDisplay), _
delim)(1)
End Function
A = "Cat" & vbcrlf & "Tiger" & vbcrlf & "Lion" & vbcrlf & "Shark hunting florida lynxs" & vbcrlf & "Leopard" & vbcrlf & "Cheetah"
A= StrReverse(A)
NumLines = 3
i=1
For X = 1 to NumLines
i = Instr(i, A, vbcr) + 1
Next
Msgbox StrReverse(Left(A, i - 1))
This is a program that cuts or leaves lines from top or bottom of files.
To use
Cut
filter cut {t|b} {i|x} NumOfLines
Cuts the number of lines from the top or bottom of file.
t - top of the file
b - bottom of the file
i - include n lines
x - exclude n lines
Example
cscript //nologo filter.vbs cut t i 5 < "%systemroot%\win.ini"
The script
Set rs = CreateObject("ADODB.Recordset")
With rs
.Fields.Append "LineNumber", 4
.Fields.Append "Txt", 201, 5000
.Open
LineCount = 0
Do Until Inp.AtEndOfStream
LineCount = LineCount + 1
.AddNew
.Fields("LineNumber").value = LineCount
.Fields("Txt").value = Inp.readline
.UpDate
Loop
.Sort = "LineNumber ASC"
If LCase(Arg(1)) = "t" then
If LCase(Arg(2)) = "i" then
.filter = "LineNumber < " & LCase(Arg(3)) + 1
ElseIf LCase(Arg(2)) = "x" then
.filter = "LineNumber > " & LCase(Arg(3))
End If
ElseIf LCase(Arg(1)) = "b" then
If LCase(Arg(2)) = "i" then
.filter = "LineNumber > " & LineCount - LCase(Arg(3))
ElseIf LCase(Arg(2)) = "x" then
.filter = "LineNumber < " & LineCount - LCase(Arg(3)) + 1
End If
End If
Do While not .EOF
Outp.writeline .Fields("Txt").Value
.MoveNext
Loop
End With