2009-06-19 28 views
3

我想存儲在excel/vba宏窗口框中的平面文件中的unicode字符串。該宏將普通字符串轉換爲unicode表示形式,需要將其存儲在文件中並稍後進行檢索。Unicode字符串從平面文件從VBA

回答

2

添加對「Microsoft Scripting Runtime」COM組件(scrrun.dll)的引用。

它具有創建/讀取/寫入文件的所有類(特別是FileSystemObject/TextStream)。

5

如上所述,您可以使用Microsoft Scripting Runtime(scrrun.dll)。我已經在下面發佈了一些例子。有些人也喜歡本地文件IO功能。有一個廣泛的(和相當全面的線程)的線程在這裏:http://www.xtremevbtalk.com/showthread.php?t=123814

但是對於Unicode文件,它可能是最痛苦的使用Textstreams :)

Public Sub StringToTextFile(ByVal path As String, ByVal value As String) 
    'Requires reference to scrrun.dll 
    Dim fso As Scripting.FileSystemObject 
    Dim ts As Scripting.TextStream 
    Set fso = New Scripting.FileSystemObject 
    Set ts = fso.CreateTextFile(path, False, True) 
    ts.Write value 
    ts.Close 
End Sub 

Public Sub LazyMansWay(ByVal path As String, ByVal value As String) 
    'Reference counting will cause the objects to be destroyed. The termination 
    'events of the classes will cause the connections to be closed. 
    CreateObject("Scripting.FileSystemObject").CreateTextFile(path, False, True).Write value 
End Sub 
+0

+1 hd post quality – 2012-08-03 11:20:24

1

我能想出最好的辦法是讀字符串中字節數組和寫入每個字節爲二進制文件

Private Function WriteBinaryFile(ByRef szData As String) 
    Dim bytData() As Byte 
    Dim lCount As Long 

    bytData = szData 
    Open PwdFileName For Binary As #1 
     For lCount = LBound(bytData) To UBound(bytData) 
      Put #1, , bytData(lCount) 
     Next lCount 
    Close #1 
End Function 

讀回由二進制模式打開該文件並讀取每個字節到字節數組,然後將其轉換爲一個字符串。

Sub ReadBinaryFile(ByRef gszData As String) 
Dim aryBytes() As Byte 
Dim bytInput As Byte 
Dim intFileNumber 
Dim intFilePos 

intFileNumber = FreeFile 

Open PwdFileName For Binary As #intFileNumber 
intFilePos = 1 

Do 
    Get #intFileNumber, intFilePos, bytInput 
    If EOF(intFileNumber) = True Then Exit Do 
    ReDim Preserve aryBytes(intFilePos - 1) 
    aryBytes(UBound(aryBytes)) = bytInput 
    intFilePos = intFilePos + 1 
Loop While EOF(intFileNumber) = False 
Close #intFileNumber 

gszData = aryBytes 
End Sub