脚本文件系统对象-无法编写文本和创建文件对象

时间:2019-05-26 19:22:58

标签: excel vba filesystemobject

我有大部分代码,但无法运行。一些基本信息是我的用户名是nywongab,我希望将其作为文本文件并将其放置在桌面上。 谢谢

Sub createsth()        
    Dim abbyFilesystem As filesystemobject    
    Dim abbyfile As File

    Set abbyFilesystem = CreateObject("scripting.filesystemobject")   
    Set abbyfile =_
        abbyFilesystem.createtextfile("C:\Users\nywongab\Desktop"_ 
        & ".txt")_

    Dim result As String
    result = "A"

    abbyfile.write (result)
End Sub

1 个答案:

答案 0 :(得分:1)

这个问题还不太清楚..尽管从主题上来说,您在写入文件时遇到了问题。从代码来看显然不起作用,但是您很亲近。

如果您尝试更动态地获取用户名或桌面路径,则可以像这样使用Environ

Sub createsth()

Dim pathDesktop As String
pathDesktop = Environ("USERPROFILE") & "\Desktop\"

Dim pathSave As String
pathSave = pathDesktop & Environ("USERNAME") & ".txt"

Dim abbyFileSystem As Object
Set abbyFileSystem = CreateObject("Scripting.FileSystemObject")

Dim abbyFile As Object
Set abbyFile = abbyFileSystem.CreateTextFile(pathSave)

Dim result As String
result = "A"

abbyFile.Write result
abbyFile.Close

End Sub