简体   繁体   中英

How to open Excel file written with incorrect character encoding in VBA

I read an Excel 2003 file with a text editor to see some markup language. When I open the file in Excel it displays incorrect characters. On inspection of the file I see that the encoding is Windows 1252 or some such. If I manually replace this with UTF-8, my file opens fine. Ok, so far so good, I can correct the thing manually.

Now the trick is that this file is generated automatically, that I need to process it automatically (no human interaction) with limited tools on my desktop (no perl or other scripting language).

Is there any simple way to open this XL file in VBA with the correct encoding (and ignore the encoding specified in the file)?

Note, Workbook.ReloadAs does not function for me, it bails out on error (and requires manual action as the file is already open).

Or is the only way to correct the file to go through some hoops? Either: text in, check line for encoding string, replace if required, write each line to new file...; or export to csv, then import from csv again with specific encoding, save as xls?

Any hints appreciated.

EDIT:

ADODB did not work for me (XL says user defined type, not defined).

I solved my problem with a workaround:

name2 = Replace(name, ".xls", ".txt")
Set wb = Workbooks.Open(name, True, True) ' open read-only
Set ws = wb.Worksheets(1)
ws.SaveAs FileName:=name2, FileFormat:=xlCSV
wb.Close False                    ' close workbook without saving changes
Set wb = Nothing                  ' free memory
Workbooks.OpenText FileName:=name2, _
                   Origin:=65001, _
                   DataType:=xlDelimited, _
                   Comma:=True

Well I think you can do it from another workbook. Add a reference to AcitiveX Data Objects, then add this sub:

Sub Encode(ByVal sPath$, Optional SetChar$ = "UTF-8")

    Dim stream As ADODB.stream
    Set stream = New ADODB.stream

    With stream
        .Open
        .LoadFromFile sPath ' Loads a File
        .Charset = SetChar  ' sets stream encoding (UTF-8)
        .SaveToFile sPath, adSaveCreateOverWrite
        .Close
    End With

    Set stream = Nothing
    Workbooks.Open sPath
End Sub

Then call this sub with the path to file with the off encoding.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM