创建文件-VBA时找不到路径

时间:2014-06-12 19:56:03

标签: vba excel-vba excel

我正在尝试创建一个文本文件并向其写入数据,这很简单。 好吧,它不起作用,我到处寻找,但找不到答案。

当它到达CreateTextFile()方法时,它会抛出路径未找到错误。但我确保路径有效且存在。

'Create a text file
Private Sub OpenFile()
Dim filePath As String
Dim fileName As String
Dim fullPath As String
Const ForAppending = 8, TristateFalse = 0
Dim curDate As Date
Dim strDate As String
curDate = Date
strDate = CStr(curDate)
fileName = "DCSSInputLitigation_" & "(" & strDate & ")" & ".txt"

filePath = "C:\TempFolder\"

Set fs = CreateObject("Scripting.FileSystemObject")
fullPath = fs.BuildPath(filePath, fileName)

Set fWriter = fs.CreateTextFile(fullPath)

End Sub

当我对方法中的路径进行硬编码时,它可以工作,但是当我使用变量时却没有。任何想法?

  Set fWriter = fs.CreateTextFile("C:\TempFolder\test.txt")

1 个答案:

答案 0 :(得分:4)

如果你得到如下日期:

strDate = CStr(curDate)

您要将/添加到文件名中,并且您创建的fullPath的字符串值为:

C:\TempFolder\DCSSInputLitigation_(6/12/2014).txt

Windows上的文件名不能包含/,因此您在这里遇到问题。

您可以格式化日期或将/替换为:

strDate = replace(CStr(curDate),"/","-")
strDate = Format(curDate,"dd-mm-yyyy")

要么工作。