|
楼主 |
发表于 2024-5-22 08:12
|
显示全部楼层
Sub filetext() '写入文本
Dim host As New CLRHost, Encoding As mscorlib.Object, utf8 As mscorlib.Object, textPath$, createText$
Call host.Initialize(False)
'On Error Resume Next
Dim asmSys As mscorlib.Assembly, SW As mscorlib.Object, writer As mscorlib.Object
host.CLRLoadAssembly ("System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")
host.CLRLoadAssembly ("System.IO, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a")
host.CLRLoadAssembly ("System.Text.Encoding, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a")
Set SW = host.CLRResolveType("System.IO.Stream")
Set Encoding = host.CLRResolveType("System.Text.Encoding")
Set utf8 = host.CLRInvokeMethod(host.CLRInvokeMethod(Encoding, "GetProperty", "UTF8"), "GetValue", Null)
textPath = ThisWorkbook.Path & "\CDriveDirs.txt"
Set writer = host.ToObject(host.CLRGetType(SW).Assembly).CreateInstance_3("System.IO.StreamWriter", False, BindingFlags_Instance Or BindingFlags_Public Or BindingFlags_CreateInstance, Nothing, Array(textPath, False, utf8), Nothing, Array())
createText = "Hello and Welcome,热烈欢迎"
host.CLRInvokeMethod writer, "Write", createText '此excel所在路径文件夹会生成一个CDriveDirs.txt,并写入utf8文本with BOM
host.CLRInvokeMethod writer, "Close"
Set SW = Nothing
Set writer = Nothing
Set Encoding = Nothing
Set utf8 = Nothing
Set host = Nothing
End Sub |
|