I want to know how I can get each line of this string until the next #.
#cnb Santander
#cnn VENTA
#br
#cnn PRUEBAS INTEGRACIONES DLL
so I can have it on different line like:
#cnb Santander
#cnn VENTA
I have tried using Split function like this:
Dim sLines() As String, L As Long
sLines = Split(Text1.Text, vbCrLf)
but it seems that vbCrLf is not working
also tried:
sLines = Split(Text1.Text, " ")
If the text was manually entered into a multiline TextBox, then each press of Return will add a CrLf combination and your code should work just fine.
Since the code doesn't work, I assume that the text is being loaded from somewhere else, and that the likely problem is that the text is Unix formatted, meaning that it only contains Lf characters, not CrLf. (I've also come across Cr on it's own before too.)
If this is the case, then you simply need to convert the line feeds first. I usually convert everything to single Lf characters when splitting like this...
Dim sLines() As String
Dim sTemp As String
sTemp = Replace$(Text1.Text, vbCrLf, vbLf) ' Convert CrLf combinations to Lf only
sTemp = Replace$(sTemp, vbCr, vbLf) ' Convert any remaining Cr's to Lf's
sLines = Split(sTemp, vbLf) ' Spilt on Lf instead of CrLf
Related
With Visual Basic, I'm confused with that the behavior of Print statement in that sometimes the following statement: would cause additional carriage return "^M" at the end of a line, but sometimes, it doesn't. I wondering why?
filePath = "d:\tmp\FAE-IMM-Report-2012-Week.org"
If Dir(filePath) <> "" Then
Kill filePath
End If
outFile = FreeFile()
Open filePath For Output As outFile
Print #outFile, "#+TITLE: Weekly Report"
would produce
#+TITLE: Weekly Report^M
while I wish without ^M:
#+TITLE: Weekly Report
In one test program, almost the same code would produce no "^M".
Please help! Thanks a lot.
Upon further experiment, I found that the following suggestion using vbNewline and ";" at the end of print content, still does not solve my problem.
After careful isolation, I found the cause of the problem is an character that seems like a space, not exactly space, followed by newline and carriage return. Before printing the text containing the offending string, there was no carriage return, but once the offending line is printed, then every line including the previous line printed would have carriage return.
I'm not sure what the exact the offending string is as my skill of VBA is not yet too well.
Here is a copy of the offending text from a spreadsheet cell:
"There is something invisible after this visible text
After the invisible text, then there might be a carriage return $Chr(13) and/or newline"
I'm not sure if the paste to web browser would preserve the content, though. By pasting to emacs, I did not see carriage return, while emacs should display it, if there is one. So I guess that there is no carriage return in the offending string.
Below is the program demonstrate the problem:
Sub DemoCarriageReturnWillAppear()
Dim filePath As String
Dim outFile
Dim offendingText
filePath = "d:\tmp\demoCarriageReturn.org"
If Dir(filePath) <> "" Then
Kill filePath
End If
outFile = FreeFile()
Open filePath For Output As outFile
Print #outFile, "#+AUTHOR: Yu Shen" & vbNewLine;
Close #outFile 'At this moment, there is no carriage return
Open filePath For Append As outFile
offendingText = ThisWorkbook.Worksheets("Sheet1").Range("A1")
Print #outFile, offendingText & vbNewLine;
Close #outFile 'Now, every line end has carriage return.
'It must be caused by something offending at the above print out content.
End Sub
Here is the final result of the above procedure:
#+AUTHOR: Yu Shen^M
There is something invisible after this visible text
After the invisible text, then there might be a carriage return $Chr(13) or newline^M
Note the above "^M" is added by me, as carriage return would not be visible in browser.
If you're interested, I can send you the excel file with the offending content.
I need your help on how to avoid those offending string, or the carriage returns.
(I even try to do string Replace of the carriage return or new line, as I found that once I manually deleted whatever caused change to another line, the problem would be gone. But calling Replace to replace vbNewline, Chr$(13), or vbCrLf did not make any difference.
Thanks for your further help!
Yu
Use a trailing semicolon to surpress the new line:
Print #outFile, "#+TITLE: Weekly Report";
^
^
The VB Editor will often add a semicolon if you make a mistake in the statement which could explain why the new line is sometimes output and sometimes not.
New diagnostic routine
We need to know the character within cell A1 that is causing the problem.
Place the following subroutine within one of your modules.
Public Sub DsplInHex(Stg As String)
Dim Pos As Long
For Pos = 1 To Len(Stg)
Debug.Print Hex(AscW(Mid(Stg, Pos, 1))) & " ";
Next
Debug.Print
End Sub
Go to VB Editor's Immediate window and type in the following text following by Return:
DsplInHex(Sheets("Sheet1").range("A1"))
Underneath this line, you should see something like 54 65 73 74 31. This is a list of the code value of each character in the cell. I expect we will see A, the code for line feed, or D, the code for carriage return, at the end of the list.
Position the cursor in cell A1. Click F2 to select edit then Backspace to delete the invisible trailing character then Return to end the edit. Go back to the Immediate Window, position the cursor to the end of DsplInHex(Sheets("Sheet1").range("A1")) and click Return. The trailing character should have gone.
Try that and report back. Good luck.
To help the other people in the future, here is an summary of my problem and the solution. The extra carriage return on each line even with semi-colon at the print statement end was actually caused by a string of space followed by newline (Chr$(A)) in one of the print statement, once such string is printed, then all previous and subsequent printed content would have an extra carriage return!
It seems a bug on VBA 6 (with Excel 2007), a nasty one!
My work-around was to replace the newline by a space.
Thanks for Tony's repeated help enabling me finally nailed down the cause.
Here is the code to demonstrate the problem:
Sub DemoCarriageReturnWillAppearOnAllLines()
Dim filePath As String
Dim outFile
Dim offendingText
filePath = "d:\tmp\demoCarriageReturn.org"
If Dir(filePath) <> "" Then
Kill filePath
End If
outFile = FreeFile()
Open filePath For Output As outFile
Print #outFile, "#+AUTHOR: Yu Shen" & vbNewLine;
Close #outFile 'At this moment, there is no carriage return
Open filePath For Append As outFile
offendingText = " " & Chr$(10)
Print #outFile, offendingText & vbNewLine;
Close #outFile 'Now, every line end has carriage return.
'It must be caused by the offending at the above print out content.
End Sub
After the first "Close #outFile", here is the content of the file demoCarriageReturn.org:
#+AUTHOR: Yu Shen
Note: with editor capable showing carriage return as visible ^M, there is no carriage return present.
However, after the second "Close #outFile", here is the content of the same file with additional content:
#+AUTHOR: Yu Shen^M
^M
Note: there are two carriage returns appear. They are not intended. Especially, to the first line, the print statement has been executed, and at the previous close statement, it was found without carriage return. (To illustrate carriage return, I have to typing ^M in web page here. But it's in the file of the print out.)
This is why I think that it's a bug, as the carriage returns are not intended. It's undesirable surprise.
The following code shows that if I filter out the linefeed character the problem would be gone.
Sub DemoCarriageReturnWillNotAppearAtAll()
Dim filePath As String
Dim outFile
Dim offendingText
filePath = "d:\tmp\demoCarriageReturn.org"
If Dir(filePath) <> "" Then
Kill filePath
End If
outFile = FreeFile()
Open filePath For Output As outFile
Print #outFile, "#+AUTHOR: Yu Shen" & vbNewLine;
Close #outFile 'At this moment, there is no carriage return
Open filePath For Append As outFile
offendingText = " " & Chr$(10)
Print #outFile, Replace(offendingText, Chr$(10), "") & vbNewLine;
Close #outFile 'Now, no more carriage return.
'The only change is removing the linefeed character in the second print statement
End Sub
After full execution of the above program, there is indeed no carriage return!
#+AUTHOR: Yu Shen
This shows that string combination of space followed by linefeed caused the bug, and removing linefeed can avoid the bug.
The following code further demonstrate that if there is no offending string, even without newline and semi-colon at the end of print statement, there would not be undesired carriage return!
Sub DemoCarriageReturnWillNotAppearAtAllEvenWithoutNewLineFollowedBySemiColon()
Dim filePath As String
Dim outFile
Dim offendingText
filePath = "d:\tmp\demoCarriageReturn.org"
If Dir(filePath) <> "" Then
Kill filePath
End If
outFile = FreeFile()
Open filePath For Output As outFile
Print #outFile, "#+AUTHOR: Yu Shen"
Close #outFile 'At this moment, there is no carriage return
Open filePath For Append As outFile
offendingText = " " & Chr$(10)
Print #outFile, Replace(offendingText, Chr$(10), "")
Close #outFile 'Now, no more carriage return.
'The real change is removing the linefeed character in the second print statement
End Sub
Also in the output result:
#+AUTHOR: Yu Shen
Still no the annoying carriage return!
This shows that using newline followed by semi-colon at the end of print statement is not the solution to the problem of carriage return at every line! The real solution is to avoid any string of space followed by linefeed in the print out content.
Yu
I have encountered something really weird. When exporting to CSV my top line shows the quotation marks yet the lines below down.
I use UTF8 encoding and manually add the double quotation marks to the value so that it is encased with quotation marks.
the code being used is
Dim fs As New IO.FileStream(GenericValueEditorExportFilename.Value, IO.FileMode.Create)
Dim writer As New IO.StreamWriter(fs, Encoding.UTF8)
fs.Write(Encoding.UTF8.GetPreamble(), 0, Encoding.UTF8.GetPreamble().Length)
....
....
....
While reader.Read
If reader("TargetLanguageID") = targetLanguageID Then
writer.WriteLine(Encode(reader("SourcePhrase")) & ", " & Encode(reader("TargetPhrase")))
End If
....
....
....
Friend Shared Function Encode(ByVal value As String) As String
Return ControlChars.Quote & value.Replace("""", """""") & ControlChars.Quote
End Function
the result when displayed in excel is shown as (https://ibb.co/ntMYdw)
when i open the file in Notepad++ the text is shown as below. But each line is displayed differently. Why is it that the 1st row displays them and the 2nd does not. Notepad++ result is displayed as (https://ibb.co/fMkWWG)
Excel is treating the first line as headers.
https://stackoverflow.com/a/24923167/2319909
So the issue was being caused by the BOM that was created to manually set the encoding for the file as a start writing to the file.
fs.Write(Encoding.UTF8.GetPreamble(), 0, Encoding.UTF8.GetPreamble().Length)
Removing this resolves by issue and the file remains in the desired UTF8 encoding as it is set on the stream writer. so there is no need to add the BOM to set the encoding.
Something like this should work for you.
Dim str As New StringBuilder
For Each dr As DataRow In Me.NorthwindDataSet.Customers
For Each field As Object In dr.ItemArray
str.Append(field.ToString & ",")
Next
str.Replace(",", vbNewLine, str.Length - 1, 1)
Next
Try
My.Computer.FileSystem.WriteAllText("C:\temp\testcsv.csv", str.ToString, False)
Catch ex As Exception
MessageBox.Show("Write Error")
End Try
I'm trying to extract my parameters from my SQL query to build my xml for an SSRS report. I want to be able to copy/paste my SQL into Excel, look through the code and find all instances of '#' and the appropriate parameter attached to it. These paramaters will ultimately be copied and pasted to another sheet for further use. So for example:
where DateField between #FromDate and #ToDate
and (BalanceFiled between #BalanceFrom and #BalanceTo
OR BalancdField = #BalanceFrom)
I know I can use Instr to find the starting position of the first '#' in a line but how then do I go about extracting the rest of the parameter name (which varies) and also, in the first two lines of the example, finding the second parameter and extracting it's variable lenght? I've also tried using the .Find method which I've been able to copy the whole line over but not just the parameters.
I might approach this problem like so:
Remove characters that are not surrounded by spaces, but do not
belong. In your example, the parentheses need to be removed.
Split the text using the space as a delimiter.
For each element in the split array, check the first character.
If it is "#", then the parameter is found, and it is the entire value in that part of the array.
My user-defined function looks something like this:
Public Function GetParameters(ByRef rsSQL As String) As String
Dim sWords() As String
Dim s As Variant
Dim sResult As String
'remove parentheses and split at space
sWords = Split(Replace(Replace(rsSQL, ")", ""), "(", ""), " ")
'find parameters
For Each s In sWords
If Left$(s, 1) = "#" Then
sResult = sResult & s & ", "
End If
Next s
'remove extra comma from list
If sResult <> "" Then
sResult = Left$(sResult, Len(sResult) - 2)
End If
GetParameters = sResult
End Function
I am extracting a column of data from a range of filenames. All my filenames are strings in the form:
Temporary PSD Report 'Month' 2011.xls
I am using Replace to extract the month from each, at the moment I am doing it in two stages which works but it seems a bit clumsy. Is there a way to use some kind of AND for multiple replacements in the same string?
Dim strfilename As String
Dim mnth As String
Dim mnthshrt As String
mnth = Replace(strfilename, "Temporary PSD Report ", "")
mnthshrt = Replace(mnth, " 2011.xls", "")
I've tried using & and AND to reference both parts to be removed but it either has no effect on the original string or produces an error.
You could also split the string at each space character and take the 4th word (index starts at 0):
s = "Temporary PSD Report 'Month' 2011.xls"
mth = Split(s, " ")(3)
This question already has answers here:
How to type Unicode currency character in Visual Basic Editor
(2 answers)
Closed 3 years ago.
I am trying to create a substitute() that will convert greek characters to latin.
The problem is that after declaring
Dim Source As String
Source = "αβγδεζηικλμνξοπρστθφω"
Source is interpreted as "áâãäåæçéêëìíîïðñóôõöù"
is there any way use unicode at declaration level?
You can try StrConv:
StrConv("αβγδεζηικλμνξοπρστθφω", vbUnicode)
Source : http://www.techonthenet.com/excel/formulas/strconv.php
[EDIT] Another solution:
You can get every greek character (lower and upper case) thanks to this procedure:
Sub x()
Dim i As Long
For i = 913 To 969
With Cells(i - 912, 1)
.Formula = "=dec2hex(" & i & ")"
.Offset(, 1).Value = ChrW$(i)
End With
Next i
End Sub
You can create an array to find the char for instance.
Source: http://www.excelforum.com/excel-programming/636544-adding-greek-letters.html
[EDIT 2] Here is a sub to build the string you wanted:
Sub greekAlpha()
Dim sAlpha As String
Dim lLetter As Long
For lLetter = &H3B1 To &H3C9
sAlpha = sAlpha & ChrW(lLetter)
Next
End Sub
As previously mentioned, VBA does support unicode strings, however you cannot write unicode strings inside your code, because the VBA editor only allows VBA files to be encoded in the 8-bit codepage Windows-1252.
You can however convert a binary equivalent of the unicode string you wish to have:
str = StrConv("±²³´µ¶·¹º»¼½¾¿ÀÁÃĸÆÉ", vbFromUnicode)
'str value is now "αβγδεζηικλμνξοπρστθφω"
Use notepad to convert the string: copy-paste the unicode string, save the file as unicode (not utf-8) and open it as ASCII (which is in fact Windows-1252), then copy-paste it into the VBA editor without the first two characters (ÿþ), which is the BOM marker
You say that your source is interpreted as "áâãäåæçéêëìíîïðñóôõöù".
Note that the Visual Basic Editor doesn't display Unicode, but it does support manipulating Unicode strings:
Dim strValue As String
strValue = Range("A1").Value
Range("B1").Value = Mid(strValue, 3)
Range("C1").Value = StrReverse(strValue)
If A1 contains Greek characters, B1 and C1 will contain Greek characters too after running this code.
You just can't view the values properly in the Immediate window, or in a MsgBox.