创建新文件和文件夹

创建新文件和文件夹
Sub Test()
Dim myDir As String
Dim Folder1 As String

StartDate = DateValue("2-Nov-2014")
NumberOfDays = 1

For N = 0 To NumberOfDays - 1
Folder1 = UCase(Format(StartDate + N, "MMM YYYY"))
Folder2 = Format(StartDate + N, "DD MMM YYYY")
If Dir("C:\GRANDVARIATIONS\FILES\" & Folder1, vbDirectory) = "" Then
MkDir "C:\GRANDVARIATIONS\FILES\" & Folder1
End If
If Dir("C:\GRANDVARIATIONS\FILES\" & Folder1 & "\" & Folder2, vbDirectory) = "" Then
MkDir "C:\GRANDVARIATIONS\FILES\" & Folder1 & "\" & Folder2
End If




On Error Resume Next
Set oDoc = GetObject(sDocPath)
Set oWord = oDoc.Parent
If Err <> 0 Then
Set oWord = CreateObject("Word.Application")
Set oDoc = oWord.Documents.Add
End If

oDoc.SaveAs ("C:\GRANDVARIATIONS\FILES\" & Folder1 & "\" & Folder2 & "\ANSWERS.Docx")
oDoc.Close

Next N
End Sub

在“FILES”文件夹中已经有“1-Nov-2014”,通过使用上述代码,我可以创建另一个名为“2-Nov-2014”的文件。

但是,在创建名为“3-Nov-2014”的文件时,我必须再次将“StartDate = DateValue(“2-Nov-2014”)”更改为“StartDate = DateValue(“3-Nov-2014”)”。

有没有一种方法可以让我不必在每次创建新文件时更改该值?

答案1

Sub Test()
Dim myDir As String
Dim Folder1 As String
Dim rRange1 As Range

Set rRange1 = Worksheets("Sheet1").Range("D3")

StartDate = Worksheets("Sheet1").Range("D3")
NumberOfDays = 1

For N = 0 To NumberOfDays - 1
    Folder1 = UCase(Format(StartDate, "MMM YYYY"))
    Folder2 = Format(StartDate + N, "DD MMM YYYY")
    If Dir("C:\GRANDVARIATIONS\FILES\" & Folder1, vbDirectory) = "" Then
        MkDir "C:\GRANDVARIATIONS\FILES\" & Folder1
    End If
    If Dir("C:\GRANDVARIATIONS\FILES\" & Folder1 & "\" & Folder2, vbDirectory) = "" Then
        MkDir "C:\GRANDVARIATIONS\FILES\" & Folder1 & "\" & Folder2
    End If




On Error Resume Next
    Set oDoc = GetObject(sDocPath)
    Set oWord = oDoc.Parent
    If Err <> 0 Then
        Set oWord = CreateObject("Word.Application")
        Set oDoc = oWord.Documents.Add
    End If

oDoc.SaveAs ("C:\GRANDVARIATIONS\FILES\" & Folder1 & "\" & Folder2 & "\ANSWERS.Docx")
oDoc.Close

Next N
End Sub

答案2

假设您想使用今天的日期来创建文件夹,请更改

StartDate = DateValue("2-Nov-2014")

到:

StartDate = DateValue(date)

如果您想要别的,那么恐怕您的问题不清楚,需要更清晰的解释。

相关内容