创建的文本已存在,就在文件名后面加(2)(3)这样怎么实现
我要创建txt或excel文档、
如果我创建的文件名已存在,则在文件名后面加编号创建。
如a已存在,创建a(2),如果在创建则a(3)。。。。。
在线等,求解释
[解决办法]
Function GetNewFileName(ByVal PathWithoutExt As String, ByVal Ext As String) As String
Dim sFileName As String
Dim i As Long
i = 1
sFileName = PathWithoutExt & Ext
While Dir(sFileName) <> ""
i = i + 1
sFileName = PathWithoutExt & "(" & i & ")" & Ext
Wend
GetNewFileName = sFileName
End Function
'调用方式
sFileName = GetNewFileName("D:\a",".txt")
Option Explicit
Private Sub Command1_Click()
Dim strPath As String, strFile As String, i As Integer
strPath = "c:\test"
strFile = "a.txt"
i = 1
Do Until Dir(strPath & strFile) = ""
i = i + 1
strFile = "a(" & IIf(i > 1, CStr(i), "") & ").txt"
Loop
Open strPath & strFile For Output As #1
Close #1
End Sub