вот вам вопрос, скажем, у меня есть процедура, которую читает текстовый файл, после чего он обрабатывает его, чтобы прочитать этот текстовый файл. Я собираюсь использовать File System Object метод. и синтаксис для него это object.OpenTextFile(filename[, iomode[, create[, format]]])
, теперь, необязательный параметр format
используется для чтения текстового файла в трех вариантах кодирования:VBA Test Кодирование текстового файла
- система по умолчанию
- ASCII
- UNICODE
мой вопрос:
Как проверить файл Кодирование заранее, чтобы я мог выбрать правильный Format
?
вот пример кода, который я использую как часть проекта, в этой функции пользователь передает тип файла либо (txt, docx, doc, rtf), если тип (rtf, doc, DOCX) реальный объект файла (документ) будет возвращен, и если файл представляет собой текстовый файл, он будет читаться построчно в новый документ и возвращает этот новый документ:
Sub test()
ReadTxtOrDocIntoDocument_1 ("C:\Test.txt")
End Sub
Function ReadTxtOrDocIntoDocument_1(ByVal DocPath As String) As Document
'in this func we only create a new doc for the text file
'because the opening of a text file in word is messy
'if the file is supported then just open it for further processing
'======================================================
If Not DocPath = "" Then 'check if the path is not empty
'make sure one temp doc exists throughout the processing time
Dim fileExt As String 'stores the file extension of the list file
fileExt = Right(DocPath, Len(DocPath) - InStrRev(DocPath, "."))
'======================================================
'let's check if the file is text or doc
Select Case LCase(fileExt)
Case "docx"
Set ReadTxtOrDocIntoDocument_1 = Documents.Open(DocPath)
Case "doc"
Set ReadTxtOrDocIntoDocument_1 = Documents.Open(DocPath)
Case "rtf"
Set ReadTxtOrDocIntoDocument_1 = Documents.Open(DocPath)
Case "txt"
'a doc that recieves the list words for comparison
Set ReadTxtOrDocIntoDocument_1 = Documents.Add
'======================================================
Dim FSO As Object
Set FSO = CreateObject("Scripting.FileSystemObject")
'======================================================
Const ForReading = 1
Const OpenAsUNICODE = -1
Const OpenAsSystemDefault = -2
'======================================================
Dim TxtFile As Object
Set TxtFile = FSO.OpenTextFile(DocPath, ForReading, , OpenAsSystemDefault)
Dim ThisLine As String
Dim i As Integer
i = 0
'======================================================
Do Until (TxtFile.AtEndOfStream) 'keep looping until end of file
ThisLine = TxtFile.ReadLine
'go to doc starting point
ReadTxtOrDocIntoDocument_1.Range.MoveStart unit:=wdStory, Count:=1
'insert text after the begining
ReadTxtOrDocIntoDocument_1.Range.InsertAfter ThisLine
'go to end of the doc
ReadTxtOrDocIntoDocument_1.Range.MoveEnd unit:=wdStory, Count:=1
'insert a new line (paragraph)
ReadTxtOrDocIntoDocument_1.Range.Paragraphs.Add
'increase counter to read next txt line
i = i + 1
Loop
'======================================================
TxtFile.Close
Set FSO = Nothing
Set TxtFile = Nothing
End Select
Else
MsgBox "no file path was provided"
Exit Function
'close the tempDoc after processing
End If
End Function
спасибо, и Черт ... этот материал требует большой работы. вот еще одна страница стека, которая говорит об этом, но для C# (http://stackoverflow.com/questions/90838/how-can-i-detect-the-encoding-codepage-of-a-text-file?rq=1) –