使用CreateTextFile时检查目标是否存在

时间:2013-08-05 13:45:46

标签: vba ms-word text-files

我正在创建一个用户填写的表单,完成后,他们单击一个命令按钮,他们输入的文本将保存为C:驱动器中名为Survey Results的文件夹中的文本文件。

目前,用户必须手动创建“调查结果”文件,如果C:驱动器中不存在,则Word中存在错误。我想在发生此错误之前检查目标是否存在,并提示用户创建文件夹或自动创建文件夹。

我在while循环中包含哪些内容来检查?

do while ()
messagebox1.open
loop




Private Sub CommandButton1_Click()
Dim FS As FileSystemObject
Set FS = New FileSystemObject
Dim MyFile As TextStream
Dim i As Integer
Dim FilePrefix As String, FileName As String, Extension As String

If CommandButton1.Enabled = True Then


FilePrefix = "C:\SurveyResults\"
Extension = ".txt"
i = 1

FileName = FilePrefix & comop & Trim(Str(i)) & Extension
Do While (FS.FileExists(FileName))
    i = i + 1
    FileName = FilePrefix & comop & Trim(Str(i)) & Extension
Loop

Set MyFile = FS.CreateTextFile(FileName)
MyFile.Write num1 & vbNewLine & num2 & vbNewLine & _
num3 & vbNewLine & num4 & vbNewLine & _
num5 & vbNewLine & num6 & vbNewLine & _
num7 & vbNewLine & num8 & vbNewLine & num9 & vbNewLine & num10 & vbNewLine & num11 _
& vbNewLine & num12 & vbNewLine & num13 & vbNewLine & num14 & vbNewLine _
& num15 & vbNewLine & num16 & vbNewLine & num17 & vbNewLine & num18 & vbNewLine & num19 & vbNewLine _
& num20 & vbNewLine & num21 & vbNewLine & num22 & vbNewLine & num23 & vbNewLine _
& num24 & vbNewLine & num25 & vbNewLine & num26 & vbNewLine & num27 & vbNewLine & num28 & vbNewLine _
& num29 & vbNewLine & num30 & vbNewLine & num31 & vbNewLine & num32 & vbNewLine & num33 & vbNewLine _
& com1a & vbNewLine & com1b & vbNewLine & com1c & vbNewLine & com1d & vbNewLine & com1e & vbNewLine _
& com1f & vbNewLine & com1g & vbNewLine & com1i & vbNewLine & com1j & vbNewLine & com1k & vbNewLine _
& com2a & vbNewLine & com2b & vbNewLine & com2c & vbNewLine & com2d & vbNewLine & com2e & vbNewLine _
& com2f & vbNewLine & com2g & vbNewLine _
& com3a & vbNewLine & com3b & vbNewLine & com3c & vbNewLine & com3d & vbNewLine & com3e & vbNewLine _
& com3f & vbNewLine _
& com4a & vbNewLine & com4b & vbNewLine & com4c & vbNewLine & com4d & vbNewLine & com4e & vbNewLine _
& com4f & vbNewLine & com4g & vbNewLine & com4h & vbNewLine & com4i & vbNewLine & com4j & vbNewLine & com4k & vbNewLine & com4l & vbNewLine _
& com5a & vbNewLine & com5b & vbNewLine & com5c & vbNewLine & com5d & vbNewLine & com5e & vbNewLine _
& com5f & vbNewLine & com5g & vbNewLine & com5h & vbNewLine & com5i & vbNewLine & com5j & vbNewLine _
& com6a & vbNewLine & com6b & vbNewLine & com6c & vbNewLine & com6d & vbNewLine _
& com1hb & vbNewLine & com1hd & vbNewLine _
& com1hf & vbNewLine & com1hh & vbNewLine & com1hj & vbNewLine & comop
End If

End Sub

1 个答案:

答案 0 :(得分:0)

执行以下代码段:

Dim FilePrefix$, fs As New Scripting.FileSystemObject
FilePrefix = "C:\SurveyResults\"
If Dir(FilePrefix, vbDirectory) <> "" Then
    'directory exists
Else
    'directory does not exist
    fs.CreateFolder FilePrefix         ' create the dir
End If