我想将 unicode 字符串存储在来自 excel/vba 宏的 windows 框中的平面文件中。该宏将普通字符串转换为 unicode 表示,需要将其存储在文件中并稍后检索。
问问题
4178 次
3 回答
6
如前所述,您可以使用 Microsoft 脚本运行时 (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
于 2009-06-19T19:14:31.320 回答
2
添加对“Microsoft Scripting Runtime”COM 组件 (scrrun.dll) 的引用。
它具有创建/读取/写入文件的所有类(特别是 FileSystemObject/TextStream)。
于 2009-06-19T04:26:56.733 回答
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
于 2009-07-24T11:03:01.367 回答