我需要将一些字符串变量保存到utf-8编码的文件中。 我有vba脚本可以从另一个应用程序中检索变量。
Sub Main
ChanNum = DDEInitiate("MacroEngine","MacroGetVar")
Var$ = DDERequest$(ChanNum,"VariableFromOutside")
DDETerminate ChanNum
sContent = Var
MsgBox sContent
End Sub
该脚本只能显示sContent,但我需要在下一个脚本中进一步处理此字符串,如下所示
Sub saveUTF_File(FileUrl,sCode)
' save text into utf-8 format
Set objStream = CreateObject("ADODB.Stream")
With objStream
.Open
.Charset = "utf-8"
.Position = objStream.Size
.WriteText=sCode
.SaveToFile FileUrl,2
.Close
End With
Set objStream = Nothing
End Sub
FilePath = "C:\file.html"
saveUTF_File FilePath,sContent
但它并不是因为sContent变量不是从Sub Main过程继承的。 我的问题是我该怎么办?感谢您提前寻求帮助。
我的代码现在是
Function TextOutside() As Variant
ChanNum = DDEInitiate("MacroEngine","MacroGetVar")
Var$ = DDERequest$(ChanNum,"VariableFromOutside")
DDETerminate ChanNum
TextOutside = Var
' MsgBox TextOutside
End Function
Sub saveUTF_File(FileUrl,sCode)
Set objStream = CreateObject("ADODB.Stream")
With objStream
.Open
.Charset = "utf-8"
.Position = objStream.Size
.WriteText=sCode
.SaveToFile FileUrl,2
.Close
End With
Set objStream = Nothing
End Sub
FilePath = "C:\file.html"
sContent = TextOutside()
saveUTF_File FilePath, sContent
下面的这个脚本没有错误,但不幸的是不想将结果保存到C:\ file.html :(为什么?
Global sContent
Sub Main()
ChanNum = DDEInitiate("MacroEngine","MacroGetVar")
Var$ = DDERequest$(ChanNum,"VariableFromOutside")
DDETerminate ChanNum
sContent = Var
MsgBox sContent
End Sub
Sub saveUTF_File(FileUrl,sCode)
' save text into utf-8 format
Set objStream = CreateObject("ADODB.Stream")
With objStream
.Open
.Charset = "utf-8"
.Position = objStream.Size
.WriteText = sCode
.SaveToFile FileUrl,2
.Close
End With
Set objStream = Nothing
End Sub
Sub DoAll()
Dim FilePath
'
' Main is called before here.
'
FilePath = "C:\file.html"
saveUTF_File FilePath, sContent
End Sub
答案 0 :(得分:3)
如果我理解你,这可能是一个解决方案,我还建议你明确声明所有变量与Dim关键字,让我们使用脏全局变量解决方案:
Global sContent
Sub Main()
ChanNum = DDEInitiate("MacroEngine","MacroGetVar")
Var$ = DDERequest$(ChanNum,"VariableFromOutside")
DDETerminate ChanNum
sContent = Var
MsgBox sContent
End Sub
Sub saveUTF_File(FileUrl,sCode)
' save text into utf-8 format
Set objStream = CreateObject("ADODB.Stream")
With objStream
.Open
.Charset = "utf-8"
.Position = objStream.Size
.WriteText=sCode
.SaveToFile FileUrl,2
.Close
End With
Set objStream = Nothing
End Sub
Sub DoAll()
Dim FilePath
'
' Main is called before here.
'
FilePath = "C:\file.html"
saveUTF_File FilePath, sContent
End Sub
在调用Main之后,通过命令按钮调用DoAll()。