0

我的代码要求用户输入文件名。我们会说我们在目录“C:\Users\aUser\Desktop\myFolder”中有 5 个文本文件。这些文本文件被命名为 A、B、C、D 和 E。

如果文本文件存在,那么我想用我已经制作的脚本覆盖内容。如果文本文件不存在,我想用他们输入的文件名制作一个,然后[使用我已经编写的脚本]填充它。

谢谢你的帮助。

4

2 回答 2

1

你解释它的方式,似乎最简单的工作流程是:

1)如果存在则删除文件

Sub test()

Dim FSO As FileSystemObject

Dim sPath As String

sPath = "U:\Test.txt"

Set FSO = New FileSystemObject
If FSO.FileExists(sPath) Then
    FSO.DeleteFile (sPath)
End If

End Sub

将脚本(我假设也是一个 txt 文件)复制到路径中: FileCopy "U:\Script", sPath

如果您在字符串变量中有脚本:

Set txtFile = FSO.CreateTextFile(sPath, True)
txtFile.WriteLine(sText)
FSO.Close
End Sub

如果脚本包含在数组中,您可以循环遍历数组并生成多个写入行。
不要忘记参考 Microsoft Scripting Runtime 库。

于 2013-01-17T15:52:01.727 回答
0

像这样的东西

  • 定位登录用户的文件夹,而不考虑操作系统
  • 检查用户输入文件是否包含在主列表中(由 持有StrFiles
  • 然后要么创建一个新文件,如果它不存在,或者
  • 为您提供一个逻辑分支来添加您的覆盖脚本

代码

GetFiles()
Dim wsShell As Object
Dim objFSO As Object
Dim objFil As Object
Dim strFolder As String
Dim StrFile As String
Dim StrFiles()
StrFiles = Array("A.txt", "B.txt", "C.txt")
Set wsShell = CreateObject("wscript.shell")
strFolder = wsShell.specialFolders("Desktop") & "\myFolder"
StrFile = Application.InputBox("Please enter A.txt, B.txt", "File Selection", , , , , 2)
If IsError(Application.Match(StrFile, StrFiles, 0)) Then
MsgBox StrFile & " is invalid", vbCritical
Exit Sub
End If
If Len(Dir(strFolder & "\" & StrFile)) = 0 Then
'make file
Set objFSO = CreateObject("scripting.filesystemobject")
Set objFil = objFSO.createtextfile(strFolder & "\" & StrFile, 2)
objFil.Close
Else
'write over file
'add your code here
End If
End Sub
于 2013-01-16T22:13:47.950 回答