我正在为名为“ScorBase”的程序编写VBA脚本。我正在尝试调用创建文本文件的子例程但我遇到此错误“506”。
这是我正在扭动的代码:
Sub emailFile()
' Declare a TextStream.
Dim stream
'As TextStream
dim fso
Set fso = New FileSystemObject
' Create a TextStream.
Set stream = fso.CreateTextFile("C:\Users\eladt\Desktop\creatFile\Mail.txt", True)
stream.WriteLine "user Email."
stream.WriteLine "Maki"
stream.WriteLine "Nigeri"
stream.WriteLine "Sashimi"
stream.Close
End Sub
答案 0 :(得分:1)
如果来自其他应用程序的后期绑定有效,则第三方应用程序托管的VBA环境存在问题,可能是它正在执行某种类型的沙盒。
您不需要任何外部库来写入文件,您可以尝试本地执行:
Dim hf As Integer
hf = FreeFile
Open "C:\Users\eladt\Desktop\creatFile\Mail.txt" For Output As #hf
Print #hf, "user Email."
Print #hf, "Maki"
Print #hf, "Nigeri"
Print #hf, "Sashimi"
Close #hf
答案 1 :(得分:1)
一种更简单的方法,不使用任何外部引用:
Sub MM_Email_To_File()
Dim FF As Integer
FF = FreeFile
'// The file will be created if it doesn't exist
Open "C:\Users\eladt\Desktop\creatFile\Mail.txt" For Output As #FF
Print #FF, "User Email"
Print #FF, "Maki"
Print #FF, "Nigeri"
Print #FF, "Sashimi"
Close #FF
End Sub
您可以查看this MSDN article以获取有关VBA中I / O操作的更多信息。
答案 2 :(得分:0)
原始问题下的评论似乎表明您的PC上未安装或未安装Microsoft Scripting Runtime。这可能是无意的,但也可能是因为IT管理员在您的环境中对该库的访问权限有限。
幸运的是,有很多种方法可以编写文本文件。您可以使用ADO库来编写流..
只需添加对Microsoft ActiveX Data Objects 2.8 Library
的引用,然后将代码替换为:
Sub emailFile()
' Declare an ADO Stream.
Dim stream As ADODB.stream
' Create an ADO Stream.
Set stream = New ADODB.stream
stream.Open
stream.Type = adTypeText
stream.WriteText "user Email.", stWriteLine
stream.WriteText "Maki", stWriteLine
stream.WriteText "Nigeri", stWriteLine
stream.WriteText "Sashimi", stWriteLine
stream.SaveToFile "C:\Users\eladt\Desktop\creatFile\Mail.txt", adSaveCreateOverWrite
stream.Close
End Sub