如何将工作表另存为具有动态名称的另一个工作簿?

时间:2014-01-06 21:03:45

标签: excel excel-vba vba

我理解如何将工作表另存为新工作簿,但如何动态指定名称? 我已经尝试了Save AsSave作为文件名,但我无法弄清楚如何将变量成功地放入名称。

Sub sheetCopy()

   Dim wbS As Workbook, wbT As Workbook
   Dim wsS As Worksheet, wsT As Worksheet
   Dim title As String

   title = ThisWorkbook.Worksheets("IR General Info").Range("B2").Text

   Set wbS = ThisWorkbook 'workbook that holds this code
   Set wsS = wbS.Worksheets("Bulk Upload")

   wsS.Copy
   Set wbT = ActiveWorkbook 'assign reference asap

   Set wsT = wbT.Worksheets("Bulk Upload")
   wsT.Name = "Exported_BulkUpload" 'rename sheet

   wbT.SaveAs wbS.Path & "\" & title & ".xlsx"

End Sub

所以,如果我用引号创建类似“boo”的标题 - 这段代码可行。但是如何根据变量标题进行更改?

2 个答案:

答案 0 :(得分:1)

您是否尝试将title变量分配给Range("B2").Value而不是Range("B2").Text

如果文件位于同一文件夹中,您可以使用wbT.SaveAs FileName:=title代替

答案 1 :(得分:0)

试试这个:

Sub sheetCopy()

   Dim wbS As Workbook, wbT As Workbook
   Dim wsS As Worksheet, wsT As Worksheet
   Dim title As String

   title = ThisWorkbook.Worksheets("IR General Info").Range("B2").Text

   '<<step through the macro and once you have gone past this point do Ctl+G to get the immediate window then type ?title in it and press enter. Or just hover your mouse over title in this script - has a value been assigned to it?   

   '<<the following line is not required - ThisWorkbook object is sufficient:
   'Set wbS = ThisWorkbook 'workbook that holds this code

   Set wsS = ThisWorkbook.Worksheets("Bulk Upload")

   wsS.Copy  '<<I've changed below here so it is saved straight away
   ActiveWorkbook.SaveAs ThisWorkbook.Path & "\" & title & ".xlsx"
   Set wbT = excel.workbooks(title & ".xlsx") 'assign reference 

   Set wsT = wbT.Worksheets("Bulk Upload")
   wsT.Name = "Exported_BulkUpload" 'rename sheet


End Sub