How can I check if a string starts (or ends) with vbCrLf?
I've tried with substring but it doesn't seem to work:
Dim s As String = ""
s &= vbCrLf & "Test"
If s.Substring(0, 1) = vbCrLf Then
MsgBox("Yes")
End If
Try this
StartsWith - checks the first part of a String.
Dim s As String = "vbCrLf bla bla bla"
If s.StartsWith("vbCrLf") Then
MsgBox("Yes")
End If
EndsWith - checks the last characters of a String.
Dim s As String = "bla bla bla vbCrLf"
If s.EndsWith("vbCrLf") Then
MsgBox("Yes")
End If
Left (and Right) can be used in place of .StartsWith/.EndsWith if you're having issues with these.
Dim s As String
s = vbCrLf & "Test"
If Left(s, Len(vbCrLf)) = vbCrLf Then
MsgBox("Yes")
End If
The simplest solution I could come up with for determining whether a string contains another string anywhere is to use the split function:
Dim s As String
Dim i As Integer
Dim v As Variant
s = vbCrLf & "Test"
i = Split(s, vbCrLf)
For Each item In i
j = j + 1
Next item
If j > 1 or vbCrLf = "" Then
MsgBox("Yes")
End If
I believe you are asking if there is a way to see if the string begins with a line brake. [Line Feed Return] (vbLf) or [Carriage Return] (vbCr). I use the Chr value to do that. Chr(13) is vbCr. Chr(10) is vbLf. You can use Asc to find out what the first Chr of a string is. Something like this;
Dim s As String = vbCr & "bla bla bla"
If Asc(s) = 13 Then
MsgBox("s strats with a Carriage Return")
else If Asc(s) = 10 Then
MsgBox("s strats with a Line Feed Return")
End If
Related
I am reading a file line by line in Excel VBA.
I have some strings for example,
" ooo"
" ooo "
I want to find the number of empty spaces in the front of the string. If I use Trim, it is removing empty spaces from both back and front of the string.
You could use the LTrim and RTrim functions. - I would assume that is faster, than looping through the string and doing character comparisons.
Public Function NumberOfLeadingSpaces(ByVal theString As String) As Long
NumberOfLeadingSpaces = Len(theString) - Len(LTrim(theString))
End Function
Public Function NumberOfTrailingSpaces(ByVal theString As String) As Long
NumberOfTrailingSpaces = Len(theString) - Len(RTrim(theString))
End Function
Function test(s As String) As Integer
Dim str As String
str = "[abcdefghijklmnopqrstuvwxyz0123456789]"
Dim spaceCounter As Integer
For i = 1 To Len(s)
If Not Mid(s, i, 1) Like str Then
spaceCounter = spaceCounter + 1
Else
Exit For
End If
Next i
test = spaceCounter
End Function
By popular request: Why use this function instead of Trim, LTrim, etc?
Well, to summarize the full explanation, not all spaces can be removed with Trim. But they will be removed with this function.
Consider this example (I'll borrow PhilS' solution for illustrative purposes):
Sub testSpaceRemoval()
Dim str1 As String
str1 = " " & Chr(32) & Chr(160) & "a"
Debug.Print Chr(34) & str1 & Chr(34)
Debug.Print NumberOfLeadingSpaces(str1)
Debug.Print test(str1)
End Sub
Result:
" a"
2
3
Here we can see that the string clearly contains 3 spaces, but the solution using LTrim only counted 2.
So, what to use?
Well, it depends. If you have a dataset where you know you won't get non-breaking characters, use Trim as much as you want! If you think you can get non-breaking characters, Trim alone will not be enough.
Characters to look out for are, quoted from the explanation linked above:
leading, trailing, or multiple embedded space characters (Unicode character set values 32 and 160), or non-printing characters (Unicode character set values 0 to 31, 127, 129, 141, 143, 144, and 157)
Trim can remove chr(32) (as demonstrated above) but not chr(160), because 32 is the regular space and 160 is a non-breaking space.
If you're a stickler for covering your behind, consider this total solution:
Function cleanSpecialCharacters(str As String) As String
bannedChars = Chr(127) & "," & Chr(129) & "," & Chr(141) & "," & Chr(143) & "," & Chr(144) & "," & Chr(157) & "," & Chr(160)
str = Application.WorksheetFunction.Clean(str)
str = Application.WorksheetFunction.Trim(str)
For Each c In Split(bannedChars, ",")
str = Replace(str, c, "")
Next
cleanSpecialCharacters = str
End Function
For OP's particular question, it would have to be a little more tailored.
Sub blanks()
cadena = Cells(1, 1)
i = Len(cadena)
Do Until Mid(cadena, i, 1) <> " "
If Mid(cadena, i, 1) = " " Then contador = contador + 1
i = i - 1
Loop
Cells(2, 1) = contador
End Sub
Sub main()
Dim strng As String
Dim i As Long
strng = " ooo "
i = 1
Do While Mid(strng, i, 1) = " "
i = i + 1
Loop
MsgBox "number of front empty spaces: " & i - 1
End Sub
or use LTrim function:
Sub main2()
Dim strng As String
strng = " ooo "
MsgBox "number of front empty spaces: " & Len(strng) - Len(LTrim(strng))
End Sub
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)
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
I have the following VBA code:
Sub read_in_data_from_txt_file()
Dim dataArray() As String
Dim i As Integer
Const strFileName As String = "Z:\sample_text.txt"
Open strFileName For Input As #1
' -------- read from txt file to dataArrayay -------- '
i = 0
Do Until EOF(1)
ReDim Preserve dataArray(i)
Line Input #1, dataArray(i)
i = i + 1
Loop
Close #1
Debug.Print UBound(dataArray())
End Sub
I'm trying to read in text line by line (assume 'sample.txt' is a regular ascii file) from a file and assign this data to consecutive elements in an array.
When I run this, I get all my data in the first value of the array.
For example, if 'sample.txt' is:
foo
bar
...
dog
cat
I want each one of these words in a consecutive array element.
What you have is fine; if everything ends up in dataArray(0) then the lines in the file are not using a CrLf delimiter so line input is grabbing everything.
Instead;
open strFileName for Input as #1
dataArray = split(input$(LOF(1), #1), vbLf)
close #1
Assuming the delimiter is VbLf (what it would be coming from a *nix system)
Here is a clean code on how to use for each loop in VBA
Function TxtParse(ByVal FileName As String) As String
Dim fs, ts As Object
Dim strdic() As String
Dim oitem As Variant
Set fs = CreateObject("Scripting.FileSystemObject")
Set ts = fs.OpenTextFile(FileName, 1, False, -2)
strdic = Split(ts.ReadAll, vbLf)
For Each oitem In strdic
If InStr(oitem, "YourString") <> 0 Then
Else
If InStr(1, oitem, vbTab) <> 0 Then
Debug.Print "Line number is : "; "'" & Replace(oitem, vbTab, "','") & "'"
Else
Debug.Print "Line number is : "; "'" & Replace(oitem, ",", "','") & "'"
End If
End If
Next
End Function
I want to remove the line break that I have in a certain text. I check in this forum how to do it and there were several answers but no one works for me at least in powerpoint.
I saw one example with left method:
If Len(myString) <> 0 Then
If Right$(myString, 2) = vbCrLf Or Right$(myString, 2) = vbNewLine Then
myString = Left$(myString, Len(myString) - 2)
End If
End If
text = Left (text, number) gives me Type mismatch error
text = Left$ (text, number) gives me compile error: Type-declaration character does not match declared data type.
I also try to replace the line break with "" but it just did nothing. It didn't gave me an error but the line break was still there.
The line break that I am using is vbCrLf
Your problem is likely that versions of PPT since 2007 don't use VBCrLf as a paragraph-ending character. This explains which versions use what characters for line or paragraph ends:
Paragraph endings and line breaks
http://www.pptfaq.com/FAQ00992_Paragraph_endings_and_line_breaks.htm
It's from the PPT FAQ site that I maintain.
For the object in which you want to remove the vbCrLf, try using
myObj.TextFrame.TextRange.Replace vbCrLf, ""
If you want to do this to a string (not an object) you can try something like this:
Sub stripStrings()
Dim longString As String
Dim stringCopy As String
longString = "first paragraph" & vbCrLf & "second paragraph" & vbCrLf & "third paragraph" & vbCrLf
stringCopy = Replace(longString, vbCrLf, "")
MsgBox "longstring is now:" & vbCrLf & longString
MsgBox "stringcopy is:" & vbCrLf & stringCopy
End Sub
As you will see, this removes the line breaks. Adapt for your purpose...
edit As Steve Rindsberg pointed out, it may be that your version of Powerpoint is using something other than vbCrLf as the paragraph delimiting character. Here is some code to help you figure this out - for each shape with text in it, it will extract the text, showing all "control characters" (ASCII value < 32) as \xnn where nn is the value of the control character (so that vbCR will display as \x13 for example):
Sub displayControlCharacters()
Dim sh As Shape
Dim t As String
For Each sh In ActivePresentation.Slides(1).Shapes
If sh.TextFrame.HasText Then
sh.Select
t = sh.TextFrame.TextRange.Text
MsgBox "The shape contains: " & vbCrLf & escapeString(t)
End If
Next sh
End Sub
Function escapeString(t As String)
Dim ii As Integer
Dim r As String
For ii = 1 To Len(t)
If Asc(Mid(t, ii, 1)) > 31 Then
r = r + Mid(t, ii, 1)
Else
r = r + "\x" + Format(Asc(Mid(t, ii, 1)), "0")
End If
Next
escapeString = r
End Function
A simple test showed that in PowerPoint 2010 you do have just \x13 at the end of a paragraph...