我尝试将路径变量与通过创建的对象一起使用,但出现错误
438: Object Doesn’t Support this Property or Method
:
Dim FSO As Object
Dim Text FileAs Object
Set FSO = CreateObject("Scripting.FileSystemObject")
Set TextFile= FSO.CreateTextFile(ThisWorkbook.Path & "\" & FSO.GetBaseName(ThisWorkbook.FullName) & "_TextFile" & ".txt")
Debug.Print TextFile.Path
这里有什么问题吗?有没有办法直接从创建的对象中获取路径?我试图避免为路径创建额外的变量。
错了
'Option Explicit
Sub Test()
Dim fso As Object
' Compile Error: Syntax error
Dim TextFileAs Object
Set fso = CreateObject("Scripting.FileSystemObject")
' With 'Option Explicit':
' Compile error: Variable not defined
' The procedure's signature ('Sub Test()') is highlighted in yellow.
' 'objFSO' is highlighted in blue. It is fairly obvious what's wrong.
' Without 'Option Explicit:
' Run-time error '424': Object required
' The whole 'Set TextFile...' line is highlighted in yellow.
' Hard to figure out what's wrong.
Set TextFile = fso.CreateTextFile(ThisWorkbook.Path & "\" _
& objFSO.GetBaseName(ThisWorkbook.FullName) & "_TextFile" & ".txt")
' Run-time error '438': Object doesn’t support this property or method
Debug.Print TextFile.Path
End Sub
正确
Option Explicit
Sub Test()
Dim fso As Object: Set fso = CreateObject("Scripting.FileSystemObject")
' To get the base name, you could just use the workbook name
' instead of the full name.
Dim TextFilePath As String: TextFilePath = ThisWorkbook.Path _
& "\" & fso.GetBaseName(ThisWorkbook.Name) & "_TextFile" & ".txt"
' TextStream object: has no path or name
Dim TextFile As Object: Set TextFile = fso.CreateTextFile(TextFilePath, True)
' e.g.
'TextFile.WriteLine "This is a test."
' Close it when done modifying:
TextFile.Close
' File object: has a path and a name
Dim tFile As Object: Set tFile = fso.GetFile(TextFilePath)
Debug.Print tFile.Name, tFile.Path
End Sub
FSO.CreateTextFile“创建指定的文件名并返回可用于读取或写入文件的 TextStream 对象。” TextStream 中没有 Path 属性,因此 Debug.Print TextFile.Path 返回错误,当然纠正了我在评论中指出的两个错误