How can I use special chars in VBA of Microsoft Word? - vba

I've created a set of macro files in Microsoft Word's VBA as a sort of a CAT tool (CAT = https://en.wikipedia.org/wiki/Computer-assisted_translation). The problem is that there are cases where I display the text needed to be translated and the user needs to input text in his own language. That might include some special chars, like "ăîâșț/ĂÎÂȘȚ", or even quotes or brackets. Is there any way to use those in some InputBox function? Or, at least, some way to let the user input the text he needs in some TextBox or something?... Or how should I approach this?... Maybe UTF-8 support would be what I need? Or?... Any help would be appreciated!...
I've tried Microsoft Word's vba function InputBox. I'm also thinking if, maybe, I would be able to create my own InputBox, with my conditions on it, I might be able to have one that accepts those chars too, or all the chars into some string variable... Here is something someone on StackOverflow says:
Is it possible to create an 'input box' in VBA that can take a text selection with multiple lines as an input? (I'm referring to gizlmo's answer...)
Here are 3 lines of code that contain that (although it's more of a how to question, not a debugging question, so those are not really needed...)
MsgBox ("Ziua " & Str(ziua) & " - " & titlurien(ziua))
titluales = InputBox("Titlul original: " & titlurien(ziua), "Ziua: " & Str(ziua) & ", Rapsodia Realitatilor " & monthname(lunanecesara) & Str(annecesar))
titluriro(ziua) = titluales
I expect the output to be exactly what he typed, whether it's quotes, brackets or special characters (like "ăîâșț"/"ĂÎÂȘȚ")...

A VBA InputBox will take any character typed or pasted into it. The characters available to type depends on the Language version of Windows and Office that the end user has installed.
Below is a test I just made with your example character string "ăîâșț/ĂÎÂȘȚ"
SpecialCharInput()
Dim str As String
str = InputBox("Enter you text", "Special Test Input Box")
Debug.Print str
End Sub
On my English language system, the only trouble it had was with the upper and lower case "ȘȚ" Turkish characters. By trouble I mean it turned those characters into question marks "??" in the result string. I'm sure though, if my system supported the Turkish language that those characters would be recognized and outputted properly.

Related

Escaping special characters in Microsoft Access 2016

I am working on a project for the company I work for, designing a database to keep track of and create project numbers. I have it up and running, but my supervisor has asked that I include user-input sanitizing to escape special characters that could cause a problem for the existing code and SQL. I have a few different user-input forms, which are just bound text boxes which get entered into my table when the form is closed. I also have one Input Box, which asks for the project number which an employee would like to update the info for.
From my understanding, a local Access database on our company server is not going to be very prone to SQL injection, and MS Access has a way of handling injection which I do not really understand. However, I am looking for a list of characters which could potentially cause problems, where they could potentially cause problems, and the best way to deal with them.
I have tried inputting a few different special characters which I know to be problematic into the text boxes on the forms, but Access just parses them straight into the record, with no errors. I DO have one function written in which replaces single apostrophes with two apostrophes, and this is used on the InputBox.
Here is the code behind the InputBox:
Private Sub btnOpenUpdate_Click()
Dim strInput$, safeInput$
strInput = InputBox("Enter the EP-Number for the project that you would like to update:", "Update Project")
safeInput = safeEntry(strInput) 'change all single apostrophes to double apostrophes '
If Len(safeInput & vbNullString) > 0 Then
If DCount("EPNumber", "tblProjects", "EPNumber = '" & safeInput & "'") > 0 Then
DoCmd.OpenForm "frmUpdateProject", , , "EPNumber = '" & safeInput & "'"
Else
MsgBox "Please enter a valid EP-Number.", vbInformation, "Error: Invalid EP-Number entered"
End If
Else
MsgBox "The field was left blank. Please enter a valid EP-number.", vbInformation, "Error: Empty field"
End If
End Sub
And here is the code behind the safeEntry function:
Public Function safeEntry(strEntry)
safeEntry = Replace(Nz(strEntry), "'", "''")
End Function
Apologies for the somewhat lengthy summary of my situation, but any help and input would be very appreciated, as I am fairly new to the world of MS Access and SQL, and I am trying my best to learn how to protect the database.

Change Font for Chinese Characters in VBA

I am trying to write a helper script for a colleague that will automatically open up all .doc(x) files in a directory, find any and all chinese characters, set their Font, save and close.
I already have a working version of this script. The file opening/saving/closing part is handled in Python/win32com and works fine. My big point of contention is still the VBA macro.
I know there is a regex (\p{Han}) that should be able to catch all Chinese characters, but this does not seem to work in VBA. Similarly, I have tried using Unicode Ranges and Chr(W). Nothing so far produced any output, let alone correct output.
Out of frustration, I made one last ditch attempt and simply inverted the search paramters. This is how it is now:
Sub FindReplace_zh(Rng As Range)
With Rng.Find
Do While .Execute(FindText:="[!A-ZÄÖÜa-zäöü0-9><_ ^11^13§$²³%#&/\+-]", MatchWildcards:=True)
If Rng.Font.Bold = True And Rng.Font.Name Like "Arial*" Then
Rng.Font.Name = "SimHei"
ElseIf Rng.Font.Bold = False And Rng.Font.Name Like "Arial*" Then
Rng.Font.Name = "SimSun"
End If
Rng.Collapse 0
Loop
End With
End Sub
AT LEAST THIS WORKS, but its far from elegant and still produces some undesired output.
I have yet to understand how I can substitute "[!A-ZÄÖÜa-zäöü0-9><_ ^11^13§$²³%#&/+-]" with a variable, or most anything else. Many characters are not covered by this regex, such as "(", ")" etc., but adding them (even escaped with ) will result in runtime errors in VBA.
I found a lot of tutorials and questions dealing with removing or inserting text, but my specific case of finding text and then changing the font, while leaving everything else untouched, seems rather specific.
Fun fact:
I had to add ^11 and ^13 to the regex list, as not including them would lead to the Macro inserting new linebreaks in random positions of the .doc
EDIT:
New try with comment:
Dim searchPattern As String
searchPattern = "[" & ChrW(&H2E80) & "-" & ChrW(&HFFED) & "]{1,}"
With Rng.Find
Do While .Execute(FindText:=searchPattern, MatchWildcards:=True)
Invalid operation on final line!
I also would not have concatinated a string like this. I am not sure how VBA parses this, but apprently not the way we hoped.
EDIT2: FIX
Removing "{1,}" from searchPattern did it. Now it works exactly as I expected it to :)
searchPattern = "[" & ChrW(&H2E80) & "-" & ChrW(&HFFED) & "]"
It is possible to find the value of characters that cannot be represented in the VBIDE by pasting them into an empty Word document and then using VBA to print the AscW values of each character in the text you wish to investigate. You can then use ChrW in VBA to reassemble the text in a VBA friendly way.
From
pinyin.info/news/2016/…
You can use the find string "[⺀-■]{1,}" to find any Chinese character. However as you have noted when you paste this text into the VBA IDE you get [?-?]{1,} because VBA uses UTD-8 as its character set. (I think).
The following code
Public Sub PrintCharacterValues()
Dim myIndex As Long
With ActiveDocument.Paragraphs(1).Range
For myIndex = 1 To 8
Debug.Print .Characters(myIndex), AscW(.Characters(myIndex)), Hex(AscW(.Characters(myIndex)))
Next
End With
End Sub
Gives the output of
" 34 22
[ 91 5B
? 11904 2E80
- 45 2D
? -19 FFED
] 93 5D
" 34 22
  160 A0
Thus you can get the critical section of the find string as
"[" & ChrW(&H2£80) & "-" & ChrW(&HFFED) &"]"

Is it possible to replace " (double quotes) with a white space in a string?

At some point of execusion of my project, the input to the database is in the format:
Buy Requirement of "xxxxxx & xxxxxx" through mycompany.com
It results in an incorrect SQL syntax error. I need to replace " with white space. I searched in google but no helpful suggestions were there.
How to replace " with whitespace?
Dim str As String
str="Buy Requirement of "Telemarketing & ERP Software" through IndiaMART.com"
' TODO: perform replace
' result
str = "Buy Requirement of Telemarketing & ERP Software through IndiaMART.com"
I finally understand what you are asking now...
Here, this is what you want to be using: teststring.Replace(""""c, "")
If you really want to use Linq and extension methods, then use this: New String(teststring.Where(Function(c) Char.IsLetterOrDigit(c) OrElse Char.IsWhiteSpace(c)).ToArray()).
But that's just making things complicated for no reason.

Escape Characters in a resource file string?

I've been globalizing an application and have been using Resx Manager to make my life easier. I ran into a multi-line string literal and it stumped me.
How would I handle the escape characters when making this string into a resource?
If Not RelayMessage(
"Are you sure you want to do the selected action?" & vbCrLf &
"A confirmation message will be sent to the user." & vbCrLf &
"Please ensure you want to perform this action before hitting accept.",
My.Resources.Confirmation, RelayMessageOptions.Confirm_YesNo) =
DialogResult.Yes
How would I make that string into a resource?
In the standard VS resource manager (is this the manager you're using?) you can enter a multi-line string resource directly in the editor by using shift-Enter:
Note that this is actually stored as a string with CR+LF pairs, assisted by the space="preserve" attribute. Viewing the .resx file in a text editor:
Results using a standard message box:
MessageBox.Show(strings.myString)
I don't know how it is usually handled in globalization problems. But an easy way would be to define your own escape character formats. For example you could define \n as a newline character. When you actually use your ressource you could then use
If Not RelayMessage(Strings.Replace(myResourceString, "\n", vbCrLf),
My.Resources.Confirmation, RelayMessageOptions.Confirm_YesNo) =
DialogResult.Yes
instead of
If Not RelayMessage(myResourceString,
My.Resources.Confirmation, RelayMessageOptions.Confirm_YesNo) =
DialogResult.Yes
Or you could manually add chars with character codes 10 and 13 (e.g. ChrW(10) & ChrW(13)) at the vbCrLf location in your ressource string. This equals a vbCrLf (meaning a carriage return (10) + line feed (13)). This would avoid manipulation of the source code. Other stuff like Tab (9) have codes, too. These are called control characters. Take a look at the wikipedia http://en.wikipedia.org/wiki/Control_character

Inserting a formula using Excel VBA

I am needing to insert a formula in using vba coding.
at the moment the line of code is
=IF(
AND(
Compliance="No",
OR(
Delivery <> "",
C31 <> ""
)
),
"Please Delete Compliance Data",
IF(
AND(
E11="",
E13="",
E23="",
E25="",
E26="",
E28="",
E30="",
E31=""),
VLOOKUP(C15,'Extrapolated RV Calculator'!B:S,18,0),
"Please complete form / SC request"
)
)"
It seems to error out on the text portions inside the code.
Any help would be appreciated.
Here are four ways to use quotation marks inside strings in VBA:
Replace "" with Chr$(34). 34 is the ASCII code for quotation marks
Use String(2,Chr$(34)) to make double quotes
Use two double quotation marks for every one (per Tim's comment)
Replace two double quotation marks with a different method, like ISBLANK for worksheet functions.
None of these is better. I usually use two double quotation marks to escape them. But sometimes I get so many quotation marks together that it's hard to read and maintain, so I'll use a different method. Here's an example:
Dim aFormula(1 To 5) As String
aFormula(1) = "=IF(AND(Compliance=""No"",OR(Delivery<>" & String(2, Chr$(34))
aFormula(2) = ",C31<>" & String(2, Chr$(34)) & ") ),"
aFormula(3) = Chr$(34) & "Please Delete Compliance Data" & Chr$(34)
aFormula(4) = ",IF(AND(ISBLANK(E11),ISBLANK(E13),ISBLANK(E23),ISBLANK(E25),ISBLANK(E26),ISBLANK(E28),ISBLANK(E30),ISBLANK(E31)),"
aFormula(5) = "VLOOKUP(C15,'Extrapolated RV Calculator'!B:S,18,0),""Please complete form / SC request""))"
Sheet1.Range("R13").Formula = Join(aFormula, vbNullString)
To empower you for the future I strongly recommend you do the following when you want to use functionality in Excel in your VBA code that you are not acquainted with yet.
Go to the developer menu and press the record macro button.
Now fill in a formula in a cell, Clear a cells content by pressing delete and clearing a cells content by going into the cell and deleting all the characters and press enter.
Now stop the macro. And go to the VBA window. See how the code is structured to accomplish these things.
Apply this also whenever you want to do other things to get a good idea of what you can use to get the results you want without having to browse around on the internet for ages!
Also watch the local variables in the locals window or Debug.Print the string you try to build to see hwat it looks so far