powered by simpleCommunicator - 2.0.53     © 2025 Programmizd 02
Форумы / Visual Basic [игнор отключен] [закрыт для гостей] / VBA Open - прикрутить кодировку в параметры
17 сообщений из 17, страница 1 из 1
VBA Open - прикрутить кодировку в параметры
    #38432680
SiNtez_26
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Гость
Всем добрый день. Вопрос такой: можно ли прикрутить к функции vba Open возможность открытия файла с определенной кодировкой? Имею ввиду следующее:
Код: vbnet
1.
2.
3.
Open cerrentFilePath For Input As #1 /*а тут надо бы залепить параметр, чтобы он открывал с корректной кодировкой*/
    Line Input #1, titles
Close #1


Спасибо!
...
Рейтинг: 0 / 0
VBA Open - прикрутить кодировку в параметры
    #38432689
Фотография Konst_One
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Участник
нет, открывай c доступом binary и массив байтов конвертируй как тебе надо для отображения
...
Рейтинг: 0 / 0
VBA Open - прикрутить кодировку в параметры
    #38432702
SiNtez_26
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Гость
Да там файлы CSV по 800 мбайт, конвертация, вероятно, может занять неимоверное количество времени.
...
Рейтинг: 0 / 0
VBA Open - прикрутить кодировку в параметры
    #38432704
SiNtez_26
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Гость
Мне надо то проверить первую строку на наличие в ней определенных значений
...
Рейтинг: 0 / 0
VBA Open - прикрутить кодировку в параметры
    #38432728
Фотография Konst_One
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Участник
такой тип доступа тоже позволяет считывать данные из файла с определённой позиции и порциями заданой длинны
...
Рейтинг: 0 / 0
VBA Open - прикрутить кодировку в параметры
    #38433046
SiNtez_26
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Гость
Окей, спасибо!
...
Рейтинг: 0 / 0
VBA Open - прикрутить кодировку в параметры
    #38439851
SiNtez_26
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Гость
Так, вообщем я возвращаюсь к теме... Каким образом нужно производить считывание данных? что-то я порылся, а информации не нашел
...
Рейтинг: 0 / 0
VBA Open - прикрутить кодировку в параметры
    #38439862
Фотография Antonariy
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Участник
Так, как хочешь ты — никак. А как правильно уже сказали.

Впрочем, если "определенная кодировка" это юникод, то можно использовать fso.OpenTextFile
...
Рейтинг: 0 / 0
VBA Open - прикрутить кодировку в параметры
    #38439867
SiNtez_26
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Гость
Да, Юникод. Можете подсказать, как считать с помощью OpenTextFile только одну строку?
...
Рейтинг: 0 / 0
VBA Open - прикрутить кодировку в параметры
    #38439894
SiNtez_26
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Гость
Вообщем, попробовал считать первую строку, вывелись кракозябры, не такой уж файл и Юникод, по всей видимости.
...
Рейтинг: 0 / 0
VBA Open - прикрутить кодировку в параметры
    #38439901
SiNtez_26
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Гость
Konst_Oneнет, открывай c доступом binary и массив байтов конвертируй как тебе надо для отображения
Касаемо данного способа, есть где об этом почитать поподробнее? Все, что находил до этого, не отличалось информативностью
...
Рейтинг: 0 / 0
VBA Open - прикрутить кодировку в параметры
    #38439937
Фотография Konst_One
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Участник
Код: vbnet
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.
18.
19.
20.
21.
22.
    Dim nFile       As Integer
    Dim sFile  as String
    Dim data as Byte	'1 байт
    Dim bytes(9) As Byte

    sFile = "C:\temp\1.bin"
    nFile = FreeFile
    Open sFile For Binary Access Read As #nFile

    If LOF(nFile) > 0 Then
'читаем первые 10 байт из файла
For i = 0 To 9
  Get nFile, , data
  bytes(i) = data
Next	

    End If
    
    Close #nFile

'тут можно конвертировать полученый массив байтов в нужный вид
...
...
Рейтинг: 0 / 0
VBA Open - прикрутить кодировку в параметры
    #38439943
Фотография Konst_One
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Участник
цикл для примера, его можно заменить на прямое чтение

т.е. вместо этого кода
Код: vbnet
1.
2.
3.
4.
5.
'читаем первые 10 байт из файла
For i = 0 To 9
  Get nFile, , data
  bytes(i) = data
Next



будет такой
Код: vbnet
1.
  Get nFile, , bytes
...
Рейтинг: 0 / 0
VBA Open - прикрутить кодировку в параметры
    #38439954
SiNtez_26
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Гость
с этим то оно ясно, спасибо, я имел ввиду сам процесс конвертации)
...
Рейтинг: 0 / 0
VBA Open - прикрутить кодировку в параметры
    #38439958
Фотография Konst_One
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Участник
ищите здесь по utf8
...
Рейтинг: 0 / 0
VBA Open - прикрутить кодировку в параметры
    #38439970
Фотография Konst_One
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Участник
полезные функции, посмотрите (вам надо наоборот сделать)

Код: vbnet
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.
18.
19.
20.
21.
22.
23.
24.
25.
26.
27.
28.
29.
30.
31.
32.
33.
34.
35.
36.
37.
38.
39.
40.
41.
42.
43.
44.
45.
46.
47.
48.
49.
50.
51.
52.
53.
54.
55.
56.
57.
58.
59.
60.
61.
62.
63.
64.
65.
66.
67.
68.
69.
70.
71.
72.
73.
74.
75.
76.
77.
78.
79.
80.
81.
82.
83.
84.
85.
86.
87.
88.
89.
90.
91.
92.
93.
94.
95.
96.
97.
98.
99.
100.
101.
102.
103.
104.
105.
106.
107.
108.
109.
110.
111.
112.
113.
114.
115.
116.
117.
118.
119.
120.
121.
122.
123.
124.
125.
126.
127.
128.
129.
130.
131.
132.
133.
134.
135.
136.
137.
138.
139.
140.
141.
142.
143.
144.
145.
146.
147.
148.
149.
150.
151.
152.
153.
154.
155.
156.
157.
158.
159.
160.
161.
162.
163.
164.
165.
166.
167.
168.
169.
170.
171.
172.
173.
174.
175.
176.
177.
178.
179.
180.
181.
182.
183.
184.
185.
186.
187.
188.
189.
190.
191.
192.
193.
194.
195.
196.
197.
198.
199.
200.
201.
202.
203.
204.
205.
206.
207.
208.
209.
210.
211.
212.
213.
214.
215.
216.
217.
218.
219.
220.
Option Explicit

Private Declare Function MultiByteToWideChar Lib "Kernel32.dll" ( _
    ByVal CodePage As Long, _
    ByVal dwFlags As Long, _
    ByVal lpMultiByteStr As Long, _
    ByVal cbMultiByte As Long, _
    ByVal lpWideCharStr As Long, _
    ByVal cchWideChar As Long _
) As Long

Private Declare Function WideCharToMultiByte Lib "Kernel32.dll" ( _
    ByVal CodePage As Long, _
    ByVal dwFlags As Long, _
    ByVal lpWideCharStr As Long, _
    ByVal cchWideChar As Long, _
    ByVal lpMultiByteStr As Long, _
    ByVal cbMultiByte As Long, _
    ByVal lpDefaultChar As Long, _
    ByVal lpUsedDefaultChar As Long _
) As Long

Private Const CP_ACP        As Long = 0         ' Default ANSI code page.
Private Const CP_UTF8       As Long = 65001     ' UTF8.
Private Const CP_UTF16_LE   As Long = 1200      ' UTF16 - little endian.
Private Const CP_UTF16_BE   As Long = 1201      ' UTF16 - big endian.
Private Const CP_UTF32_LE   As Long = 12000     ' UTF32 - little endian.
Private Const CP_UTF32_BE   As Long = 12001     ' UTF32 - big endian.

Private Sub Command_Click()

    Dim nCodePage                   As Long
    Dim iFileNoInput                As Integer
    Dim iFileNoOutput               As Integer
    Dim abytFileContents()          As Byte
    Dim nDataSize                   As Long
    Dim sFileContents               As String

    iFileNoInput = FreeFile

    nCodePage = OpenForInput("C:\input.txt", iFileNoInput)

    ' We want to read the entire contents of the file (not including any BOM value).
    ' After calling OpenForInput(), the file pointer should be positioned after any BOM.
    ' So size file contents buffer to <file size> - <current position> - 1.
    nDataSize = LOF(iFileNoInput) - Seek(iFileNoInput) - 1
    ReDim abytFileContents(1 To nDataSize)
    Get #iFileNoInput, , abytFileContents()

    Close iFileNoInput

    ' Now we must convert this to UTF-8. But we have to first convert to the Windows NT standard UTF-16 LE.
    sFileContents = FromCPStringToVBString(abytFileContents(), nCodePage)

    ' And then to UTF8.

    iFileNoOutput = FreeFile

    OpenForOutput "C:\output.txt", iFileNoOutput

    PrintUTF8 iFileNoOutput, sFileContents

    Close iFileNoOutput

End Sub

' Take a string whose bytes are in the byte array <the_abytCPString>, with code page <the_nCodePage>, convert to a VB string.
Private Function FromCPStringToVBString(ByRef the_abytCPString() As Byte, ByVal the_nCodePage As Long) As String

    Dim sOutput                     As String
    Dim nValueLen                   As Long
    Dim nOutputCharLen              As Long

    ' If the code page says this is already compatible with the VB string, then just copy it into the string. No messing.
    If the_nCodePage = CP_UTF16_LE Then
        FromCPStringToVBString = the_abytCPString()
    Else

        ' Cache the input length.
        nValueLen = UBound(the_abytCPString) - LBound(the_abytCPString) + 1

        ' See how big the output buffer will be.
        nOutputCharLen = MultiByteToWideChar(the_nCodePage, 0&, VarPtr(the_abytCPString(1)), nValueLen, 0&, 0&)

        ' Resize output byte array to the size of the UTF-8 string.
        sOutput = Space$(nOutputCharLen)

        ' Make this API call again, this time giving a pointer to the output byte array.
        MultiByteToWideChar the_nCodePage, 0&, VarPtr(the_abytCPString(1)), nValueLen, StrPtr(sOutput), nOutputCharLen

        ' Return the array.
        FromCPStringToVBString = sOutput

    End If

End Function

' Analogue of 'Open "fileName" For Input As #fileNo' - but also return what type of text this is via a Code Page value.
' There are only five valid return values:
'   CP_ACP        ANSI code page
'   CP_UTF16LE    UTF-16 Little Endian (VB and NT default string encoding)
'   CP_UTF16BE    UTF-16 Big Endian
'   CP_UTF32LE    UTF-32 Little Endian
'   CP_UTF32BE    UTF-32 Big Endian
Private Function OpenForInput(ByRef the_sFilename As String, ByVal the_iFileNo As Integer) As Long

    ' Note if we want to take account of every case, we should read in the first four bytes and check for UTF-32 low and high endian BOMs, then
    ' check for the first two bytes to check for UTF-16 low and hight endian BOMs.
    Dim abytBOM(1 To 4)  As Byte
    Dim nCodePage       As Long

    Open the_sFilename For Binary Access Read As #the_iFileNo

    ' Pull in the first four bytes to determines the BOM (byte order marker).
    Get #the_iFileNo, , abytBOM()

    ' The following are the BOMs for text files:
    '
    ' FF FE         UTF-16, little endian
    ' FE FF         UTF-16, big endian
    ' FF FE 00 00   UTF-32, little endian
    ' 00 00 FE FF   UTF-32, big-endian
    '
    ' Work out the code page from this information.

    ' Default value.
    nCodePage = CP_ACP

    Select Case abytBOM(1)
    Case &HFF
        If abytBOM(2) = &HFE Then
            If abytBOM(3) = 0 And abytBOM(4) = 0 Then
                nCodePage = CP_UTF32_LE
            Else
                nCodePage = CP_UTF16_LE
            End If
        End If
    Case &HFE
        If abytBOM(2) = &HFF Then
            nCodePage = CP_UTF16_BE
        End If
    Case &H0
        If abytBOM(2) = &H0 And abytBOM(3) = &HFE And abytBOM(4) = &HFF Then
            nCodePage = CP_UTF32_BE
        End If
    End Select

    ' Reset the file pointer to the beginning of the file.
    Select Case nCodePage
    Case CP_ACP
        Seek #the_iFileNo, 1
    Case CP_UTF16_BE, CP_UTF16_LE
        Seek #the_iFileNo, 3
    End Select

    OpenForInput = nCodePage

End Function

' Analogue of 'Open "fileName" For Append As #fileNo'
Private Sub OpenForAppend(ByRef the_sFilename As String, ByVal the_iFileNo As Integer)

    ' Open the file and move to the end of the file.
    Open the_sFilename For Binary Access Write As #the_iFileNo
    Seek the_iFileNo, LOF(the_iFileNo) + 1

End Sub

' Analogue of 'Open "fileName" For Output As #fileNo'
Private Sub OpenForOutput(ByRef the_sFilename As String, ByVal the_iFileNo As Integer)

    ' Ensure we overwrite the file by deleting it ...
    On Error Resume Next
    Kill the_sFilename
    On Error GoTo 0

    ' ... before creating it.
    Open the_sFilename For Binary Access Write As #the_iFileNo

End Sub

' Analogue of the 'Print #fileNo, value' statement. But only one value allowed.
' Setting <the_bAppendNewLine> = False is analagous to 'Print #fileNo, value;'.
Private Sub PrintUTF8(ByVal the_iFileNo As Integer, ByRef the_sValue As String, Optional ByVal the_bAppendNewLine As Boolean = True)

    Const kbytCarriageReturn        As Byte = 13
    Const kbytNewLine               As Byte = 10

    Put #the_iFileNo, , ToUTF8(the_sValue)

    If the_bAppendNewLine Then
        Put #the_iFileNo, , kbytCarriageReturn
        Put #the_iFileNo, , kbytNewLine
    End If

End Sub

' Converts a VB string (UTF-16) to UTF8 - as a binary array.
Private Function ToUTF8(ByRef the_sValue As String) As Byte()

    Dim abytOutput()                As Byte
    Dim nValueLen                   As Long
    Dim nOutputByteLen              As Long

    ' Cache the input length.
    nValueLen = Len(the_sValue)

    ' See how big the output buffer will be.
    nOutputByteLen = WideCharToMultiByte(CP_UTF8, 0&, StrPtr(the_sValue), nValueLen, 0&, 0&, 0&, 0&)

    ' Resize output byte array to the size of the UTF-8 string.
    ReDim abytOutput(1 To nOutputByteLen)

    ' Make this API call again, this time giving a pointer to the output byte array.
    WideCharToMultiByte CP_UTF8, 0&, StrPtr(the_sValue), nValueLen, VarPtr(abytOutput(1)), nOutputByteLen, 0&, 0&

    ' Return the array.
    ToUTF8 = abytOutput

End Function

...
Рейтинг: 0 / 0
VBA Open - прикрутить кодировку в параметры
    #38440009
Фотография Antonariy
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Участник
SiNtez_26Вообщем, попробовал считать первую строку, вывелись кракозябры, не такой уж файл и Юникод, по всей видимости.По все видимости открываешь неправильно.

Код: plaintext
1.
OpenTextFile(FileName As String, [IOMode As IOMode = ForReading], [Create As Boolean = False], [Format As Tristate = TristateFalse])

Последний параметр отвечает за кодировку, поиграй с ним.
...
Рейтинг: 0 / 0
17 сообщений из 17, страница 1 из 1
Форумы / Visual Basic [игнор отключен] [закрыт для гостей] / VBA Open - прикрутить кодировку в параметры
Целевая тема:
Создать новую тему:
Автор:
Закрыть
Цитировать
Найденые пользователи ...
Разблокировать пользователей ...
Читали форум (0):
Пользователи онлайн (0):
x
x
Закрыть


Просмотр
0 / 0
Close
Debug Console [Select Text]