如何在文件夹中创建文件夹,文件和保存文件

时间:2017-10-25 18:26:45

标签: excel vba

编辑:我的问题不够清楚

Sub NewWB2()
Dim wb As Workbook
Dim POname As String
Dim lrow As Long
Dim NewfolderPath As String

lrow = Cells(Rows.Count, 3).End(xlUp).Row
POname = Worksheets("Sheet1").Cells(lrow, 10).Value 'name I want for both the folder and the document

MkDir "C:\Users\First.Last\Desktop" & "\" & POname 'creates the folder in the path I want
NewfolderPath = "C:\Users\First.Last\Desktop\" & POname ' variable to define that path

Set wb = Workbooks.Add("C:\Users\First.Last\Documents\Custom Office Templates\PO Template.xltm") ' creates from template
ActiveWorkbook.SaveAs Filename:=POName 'Saves file as variable "POname"

End Sub

这里的一切都有效。我需要做的就是添加一行代码,将新工作簿保存在我创建的文件夹中。我无法找到如何做到这一点,也不知道如何添加它。

2 个答案:

答案 0 :(得分:0)

您能提供正在使用的POname的字符串示例吗? 我想你错过了NewfolderPath中的'\':

尝试:

Sub NewWB2()
    Dim wb As Workbook
    Dim POname As String
    Dim lrow As Long
    Dim NewfolderPath As String

    lrow = Cells(Rows.Count, 3).End(xlUp).Row 'finds the last row
    POname = Worksheets("Sheet1").Cells(lrow, 10).Value 'name of Folder and File
    NewfolderPath = "C:\destinationfoldername\" & POname

    MkDir NewfolderPath 'creates the new folder with the name defined above
    Set wb = Workbooks.Add("C:\folderwithtemplate\Template.xltm") 'creates new wb from template

    ActiveWorkbook.SaveAs NewfolderPath & "\" & POname
End Sub

答案 1 :(得分:0)

试试这个,猜你错过了你的文件名:

ActiveWorkbook.SaveAS Filename:=NewfolderPath & "\" & POname & "\Filename" 

如果您使用变量作为文件名,请尝试:

ActiveWorkbook.SaveAS Filename:=NewfolderPath & "\" & POname & "\" & Filename