在保存时将ComboBox项添加到文件名

时间:2013-12-17 21:51:47

标签: vba excel-vba excel-2007 excel

目前,我可以使用以下代码将活动工作表另存为新的硬编码工作表名称:

Sub SaveSheet()
    Dim FName As String
    ActiveSheet.Copy
    With ActiveSheet.UsedRange
        .Copy
        .PasteSpecial xlValues
        .PasteSpecial xlFormats
    End With
    Application.CutCopyMode = False
    FName = "C:\Users\somebody\Documents\TestSheet" & Format(Range("E19"), "mmm-d-yyyy") & ".xlsm"
    ActiveWorkbook.SaveAs Filename:=FName, _
                          FileFormat:=xlOpenXMLWorkbookMacroEnabled
End Sub

正如您所看到的那样,新工作表现在将TestSheet.slxm存储在目录中,而不是硬编码我的名字UserForm1,如下所示:

enter image description here

并已填充为:

Private Sub UserForm_Initialize()
 With ComboBox1
   .AddItem "Region 1"
   .AddItem "Region 2"
   .AddItem "Region 3"
   .AddItem "Region 4"
   .AddItem "Region 4"
 End With
End Sub

现在请您告诉我如何获取所选项目(地区)的名称并添加到:FName而不是该硬编码名称(测试表)

由于

1 个答案:

答案 0 :(得分:1)

将其放在命令按钮的click事件中。这样的事情。

Private Sub CommandButton1_Click()
    Dim FName As String

    ActiveSheet.Copy
    With ActiveSheet.UsedRange
        .Copy
        .PasteSpecial xlValues
        .PasteSpecial xlFormats
    End With

    If ComboBox1.ListIndex < 0 Then Exit Sub

    FName = "C:\Users\somebody\Documents\" & _
            ComboBox1.Value & _
            Format(Range("E19"), "mmm-d-yyyy") & ".xlsm"

    ActiveWorkbook.SaveAs Filename:=FName, _
                          FileFormat:=xlOpenXMLWorkbookMacroEnabled
End Sub