0
votes

I'm trying to write a script in VBScript which should open Microsoft Word and write down some text. The script works as expected as long as the text I'm writing is in English. However, when the text is in Hebrew or in Chinese I only get Gibberish in MS Word.

I tried to save the script file as UTF-8, but I can no longer run it after this change. I also tried to wrap it so it will be a wsf script and it didn't worked either. Couldn't find any other suggestion on Google.

Here is the script (This time I'm trying to write the word "שלום" in Hebrew).

Set objWord = CreateObject("Word.Application")
objWord.Visible = True
Set fso = CreateObject("Scripting.FileSystemObject")
Set objDoc = objWord.Documents.Add()
Set objSelection = objWord.Selection
objSelection.TypeText "שלום"

When I run this script, it opens MS word and write down "ùìåí" instead of "שלום".

1

1 Answers

1
votes

You can save a script file with the following encoding:

  1. ANSI. Only 256 chars can be used: 0..127 is standard ASCII, and upper part depends on locale you have chosen in system settings, or overridden by SetLocale().
  2. Unicode (UCS-2 or UTF-16, Little Endian). It works if saved with BOM, or without BOM. There is 1 112 064 available chars. In my opinion it is the easiest way for you to get your script to work. But file size increased by 2 times.
  3. UTF-8. Encodes any symbol in Unicode code space. Script can be ran only if saved without BOM.
  4. UTF-8 as .wsf file with first tag <?XML version="1.0" encoding="UTF-8"?>
  5. ANSI, but put all strings like WScript.Echo ChrW(1513) & ChrW(1500) & ChrW(1493) & ChrW(1501).

Notepad++ and Notepad2 are handy to clearly set the necessary encoding.

Regarding item 3. Generally, Windows Script Host is unable to run script file in UTF-8 encoding with BOM, and recognizes each byte of UTF-8-encoded file without BOM as ANSI-encoded char, while downloading the file into memory. I can suggest a work-around that allows to rectify incorrectly recognized chars being contained in variables, but you know, Unicode is a better way. Here is example:

s = "שלום"
WScript.Echo s ' wrong encoding
r = FixChars(s)
WScript.Echo r ' שלום

Function FixChars(s)
    Dim r, p
    r = ""
    For p = 1 To Len(s)
        r = r & ChrB(Asc(Mid(s, p, 1)))
    Next
    With CreateObject("ADODB.Stream")
        .Type = 2
        .Mode = 3
        .Charset = "Unicode" ' HKLM\SOFTWARE\Classes\MIME\Database\Charset
        .Open
        .WriteText r
        .Position = 0
        .Charset = "UTF-8"
        r = .ReadText
        .Close
    End With
    Do While LeftB(r, 2) = ChrB(&HFD) & ChrB(&HFF)
        r = MidB(r, 3)
    Loop
    FixChars = r
End Function

You shouldn't change locale via SetLocale() from script start till FixChars() completion, otherwise it will give an error.

And the following code is an example for item 4:

<?XML version="1.0" encoding="UTF-8"?>
<job>
<script language="VBScript">
<![CDATA[
WScript.Echo "שלום"
]]>
</script>
</job>