I want to copy a text file to another by escaping the special characters in the text and enclosing the output withing double quotes
For example. consider the input file to be:
ABC"hi%"
bcd
i want the output to be
"ABC" + "" + "hi%" + "" +vbCRLF + "bcd"
in a single line.
the script should dynamically add carriage return and linefeed at the end of each line in the input text.
any help is appreciated.
thanks
You should be able to do this using a series of Replace() statements.
s = objTextStream.ReadAll()
s = Replace(s, """", """""")
s = Replace(s, vbTab, """ & vbTab & """)
s = Replace(s, vbCrLF, """ & vbCrLf & """)
....
' Add quotes around the whole string
s = """" & s & """"
Because of the need to concatenate, however, you could end up with some empty strings in the final result. For example, if you had consecutive tabs, your output string would look something like this:
"some text" & vbTab & "" & vbTab & "" & vbCrLf & "Line2"
So you may have to do one final Replace() to get rid of those:
s = Replace(s, "& """" &", "&")
Related
I'm currently trying to create a pattern to capture a name that generally is text [A-ZÅÄÖ] but there could be one or two numeric characters.
Here is one example: (there are more fields than this, this is just an example)
PT22 111222333 2 BROTHERS RP02 570244222333
PT25 888222333 THIS TIME IT'S ONLY TEXT RP01 888244222333
I'm trying to get 2 BROTHERS and THIS TIME IT'S ONLY TEXT in this tab delimited string (rows are for eached).
When I used the pattern "(\b[A-ZÅÄÖ \&\.\´\:-_]+\b)" it captured BROTHERS, if I add 0-9 in the pattern it takes either PT22 or 111222333 if the first field is empty.
So what I would need is something that captures the field that has at least three characters that is A-ZÅÄÖ and maximum 2 characters 0-9.
Is that even possible or do I need to loop through the fields and count each type of character to determine if I'm in the correct field or not?
The fields are not in the same order every time.
My backup plan is to split on tab, and loop. On each field remove all [0-9] characters and count.
That way I will get how many [0-9] and how many [A-ZÅÄÖ] (+other) there is, and that could be used I think to find the correct field.
I am not an regex expert, maybe it is possible, but I usually find it too hard to figure this out - and ending with an regex where you're not 100% sure it fits, plus it is hard to figure out what it does once you come back to it.
I would use a small function that simply count the number of chars and digits of a string. Easy to write, easy to read, easy to adapt. Could look like
Function checkWord(s As String) As Boolean
Const minChars = 3
Const maxDigits = 2
Dim i As Long, digits As Long, chars As Long
For i = 1 To Len(s)
Select Case AscW(Mid(s, i, 1))
Case AscW("A") To AscW("Z"), AscW("Ä"), AscW("Ö"), AscW("Å"):
chars = chars + 1
Case Asc("0") To Asc("9"):
digits = digits + 1
Case Else
' Think about what happens with all other characters...
End Select
Next
checkWord = (chars >= minChars And digits <= maxDigits)
End Function
Without RegEx:
Can't you turn the logic around and remove parts you don't want:
Loop over each value;
Your values are tab-delimited so split on VbTab;
Loop over each sub-element;
Test each sub-element with the Like() operator and check that it's not numeric.
To test this I came up with the following dummy-code:
Sub Test()
Dim r As Variant: r = Array("PT22" & vbTab & "111222333" & vbTab & "2 BROTHERS" & vbTab & "RP02" & vbTab & "570244222333", "PT25" & vbTab & "888222333" & vbTab & "THIS TIME IT'S ONLY TEXT" & vbTab & "RP01" & vbTab & "888244222333")
For Each el In r
For Each SubEl In Split(el, Chr(9))
If Not SubEl Like "??[0-9][0-9]" And Not IsNumeric(SubEl) Then
Debug.Print SubEl
Exit For
End If
Next
Next
End Sub
With RegEx:
If regex is a must, try to capture what you do want:
Sub Test()
Dim r As Variant: r = Array("PT22" & vbTab & "111222333" & vbTab & "2 BROTHERS" & vbTab & "RP02" & vbTab & "570244222333", "PT25" & vbTab & "888222333" & vbTab & "THIS TIME IT'S ONLY TEXT" & vbTab & "RP01" & vbTab & "888244222333")
With CreateObject("vbscript.regexp")
.Global = True
.Pattern = "(?:^|\s)((?:[A-ZÅÄÖ]+(?:[ &.'_-][A-ZÅÄÖ]+)*\s?)?(?:\b\d\d?\b)?(?:\s?[A-ZÅÄÖ]+(?:[ &.'_-][A-ZÅÄÖ]+)*)?)(?:\s|$)|."
For Each el In r
Debug.Print Trim(.Replace(el, "$1"))
Next
End With
End Sub
Or, again remove only those parts you don't want:
Sub Test()
Dim r As Variant: r = Array("PT22" & vbTab & "111222333" & vbTab & "2 BROTHERS" & vbTab & "RP02" & vbTab & "570244222333", "PT25" & vbTab & "888222333" & vbTab & "THIS TIME IT'S ONLY TEXT" & vbTab & "RP01" & vbTab & "888244222333")
With CreateObject("vbscript.regexp")
.Global = True
.Pattern = "\s*\b(?:[A-Z]{2}\d\d|\d{3,})\b\s*"
For Each el In r
Debug.Print .Replace(el, "")
Next
End With
End Sub
Results:
All above options would print:
2 BROTHERS
THIS TIME IT'S ONLY TEXT
I have the following formula that I want to insert into a cell but it has multiple double quotes and I can't seem to make it work. There is plenty of solutions on the web but most have 1 or 2 sets of double quotes. I tried double quotes on all double quotes but it gives me a runtime error 438 object doesn't support this property
Here is the formula that I want to insert:
="Closing Costs" & " Current Buffer" & " " &TEXT('Closing Costs'!D32,"$ 0")
Here is the code that is not working:
ActiveSheet.Range("F18").Value = "=""Closing Costs"" & ""
Current Buffer"" & "" "" &TEXT('Closing Costs'!D32,""$ 0"")"
The following should work (all on one line):
ActiveSheet.Range("F18").Value = "=""Closing Costs"" & "" Current Buffer"" & "" "" &TEXT('Closing Costs'!D32,""$ 0"")"
It looks the same as your sample - but perhaps looks here are deceptive.
Using the chr() command can be helpful in these scenarios. chr(34) returns a double quote character, so the below should do the trick.
ActiveSheet.Range("F18").Value = "=" & chr(34) & "Closing Costs Current Buffer" & chr(34) & " " & chr(34) & TEXT('Closing Costs'!D32," & chr(34) & "$ 0" & chr(34) & ")"
It’s a little bit longer, but I find using chr(34) to be a little easy to determine quotation placement.
I have a problem with the following OnTime line:
Application.OnTime printTaskTimers(UBound(printTaskTimers)), _
"'PrintTask """ & cRng.Value & """, " & cRng.Offset(0, 1).Value & " '"
cRng.Value is worksheet name and cRng.Offset(0, 1).Value is the number of pages. It works correctly for all normal sheet names, apart from 2 which contain apostrophe. The apostrophe is important and I would rather adjust the code than change worksheet names. Is there any way around it?
You already know how to escape double quotes in a string. Single quotes are escaped the same way.
Application.OnTime printTaskTimers(UBound(printTaskTimers)), _
"'PrintTask """ & Replace(cRng.Value, "'", "''") & """, " & cRng.Offset(0, 1).Value & " '"
I'm trying to create a formula in the A1 cell which contains an ampersand character that looks something like this in Excel:
="Hello, "&A2
My VBA code is as follows:
Worksheets("Sheet1").Range("A1").Formula = "=""Hello, "" & "&A2"
VBA is throwing errors, and I can't figure out why. I've tried using double ampersands, and double quotes in various places and can't get around this error.
Consider:
Sub dural()
Range("A1").Formula = "=" & Chr(34) & "Hello" & Chr(34) & "& A2"
End Sub
Please consider this pithy line:
[a1] = "=""Hello, "" & A2"
...which will evaluate to, "Hello, Dave"
You have one extra ":
Worksheets("Sheet1").Range("A1").Formula = "=""Hello, "" & A2"
Use the & character code of 38:
Worksheets("Sheet1").Range("A1").Formula = "=" & Chr(34) & "Hello, " & Chr(34) & Chr(38) & "A2"
This should work as well.
ActiveCell.FormulaR1C1 = "=""hello "" & A2"
I've searched extensively for the answer to my question and I'm at an impasse.
I'm trying to pass a formula to excel with applescript. The problem is the quotes around the spaces that I want to place between fields. I've used "\" to escape the quotes but it throws an error. To make it more complicated the row number is a variable "i". Here is the formula in excel format:
=CONCATENATE(A2," ",B2," ",C2," ",D2)
Here is the formula in applescript-ese (works but does not produce spaces in data):
set rowCount to (((count of rows of used range of active sheet)) + 1)
repeat with i from rowCount to 2 by -1
set formula of row i of column 15 to "=CONCATENATE(A" & i & "," & ",B" & i & "," & ",C" & i & "," & ",D" & i & ")"
Here is the formula with escaped quotes to add the spaces (gives error):
set formula of row i of column 15 to"=CONCATENATE(A" & i & ","\" \" & ",B" & i & ","\" \" & ",C" & i & ","\" \" & ",D" & i & ")"
I get a sytax error on the first slash; Expected end of line etc. but found unknown token. I have a feeling I'm either missing a few sets of double quotes or I'm making this way more complicated than it needs to be. Any ideas? Should I be going about this differently?
Thanks in advance!
EDIT
Taking another look at it I think you have too many quotes when you use the \ character to escape the double quote. Instead of ","\" \" & ",B" try ",\" \",B" so your line would look like this:
set formula of row i of column 15 to "=CONCATENATE(A" & i & ",\" \",B" & i & ",\" \",C" & i & ",\" \",D" & i & ")"
In excel VBA you can double quote a double quote to get it to show up in a string like this:
"=CONCATENATE(A" & i & "," & """ """ & ",B" & i & "," & """ """ & ",C" & i & "," & """ """ & ",D" & i & ")"
Or you can try using ascii character for space which is Chr(32)