vba utf8 파일 읽기, 쓰기

엑셀의 한 셀에 들어가는 글자수 제한이 있다.(약 32,000글자)
32,000글자는 생각보다 크지 않기 때문에 웹에서 스크래핑한 데이터가 짤리기 십상이다. 이러한 경우 mid함수를 써서 나눠서 출력할수도 있으나 파일을 만들어 보는 것도 좋다.

Sub test()

    '바탕화면 경로
    desktop_path = CreateObject("WScript.Shell").SpecialFolders("Desktop")

    '바탕화면에 text.txt 파일
    file_name = desktop_path & "\test.txt"
    
    '파일쓰기
    Call TextStrimWrite(file_name, "Hello, world")
    
    '파일읽기
    MsgBox TextStrimRead(file_name)
        
End Sub

Function TextStrimRead(strPathName)
    Dim objStream: Set objStream = CreateObject("ADODB.Stream")
    objStream.Open
    objStream.Type = 2 'adTypeText
    objStream.Charset = "UTF-8"
    objStream.LoadFromFile strPathName
    TextStrimRead = objStream.ReadText
    Set objStream = Nothing
End Function

Sub TextStrimWrite(strPathName, strString)
    Set objStream = CreateObject("ADODB.Stream")
    objStream.Charset = "UTF-8"
    objStream.Open
    objStream.WriteText strString
    Set BinaryStream = CreateObject("adodb.stream")
    BinaryStream.Type = 1
    BinaryStream.Mode = 3
    BinaryStream.Open
    objStream.Position = 3
    objStream.CopyTo BinaryStream
    objStream.Flush
    objStream.Close
    BinaryStream.SaveToFile strPathName, 2
    BinaryStream.Close
    Set objStream = Nothing
    Set BinaryStream = Nothing
End Sub

vbs로도 잘 작동한다.

vbs 테스트

한글을 쓸때 글자가 깨지는데 개선이 필요하다.

출처
http://blog.naver.com/atmyhome/90154596931
http://blog.naver.com/PostView.nhn?blogId=program114&logNo=220684696095

답글 남기기

이메일 주소는 공개되지 않습니다. 필수 필드는 *로 표시됩니다