我使用excel宏创建了一个应用程序,用户在其中提供某些值并使用按钮单击宏将其保存到多个目录路径。
当我从下拉列表中选择一个区域时,它应该将文件保存到指定的区域文件夹。比如说,当选择NY时,文件将保存到共享驱动器和2016 - NY文件夹。但是现在,决定应用程序的未来,我正在考虑使用#34; year"作为工作表中的单独字段,它从用户检索年份值。如何在不必每年更改代码的情况下实现此目的。这个过程将继续进行,因为' n'从现在开始的年数。提前致谢 !
FileName1 = Range("D3").Value
filenameOfNewBook = FileName1
If location = "Illinois" Then
ActiveWorkbook.SaveAs FileName:="W:\Audits\2016\Illinois\" & FileName1 & "-" & "checklist" & ".xlsm"
ElseIf location = "LA" Then
ActiveWorkbook.SaveAs FileName:="W:\Audits\2016\LA\" & FileName1 & "-" & "checklist" & ".xlsm"
ElseIf location = "NY" Then
ActiveWorkbook.SaveAs FileName:="W:\Audits\2016\NY\" & FileName1 & "-" & "checklist" & ".xlsm"
Else
ActiveWorkbook.SaveAs FileName:="W:\Audits\2016\Atlanta\" & FileName1 & "-" & "checklist" & ".xlsm"
End If
MsgBox "File Saved successfully!", , "Save"
ActiveWorkbook.save
Application.DisplayAlerts = True
答案 0 :(得分:1)
根据我的办公任务经验,最好不要参考当前年份,而是用户设置的年份,因此例如在2017年1月,用户仍然可以对与2016年相关的文件执行操作。您可以删除以下内容:
If location = "Illinois" Then
ActiveWorkbook.SaveAs FileName:="W:\Audits\2016\Illinois\" & FileName1 & "-" & "checklist" & ".xlsm"
ElseIf location = "LA" Then
ActiveWorkbook.SaveAs FileName:="W:\Audits\2016\LA\" & FileName1 & "-" & "checklist" & ".xlsm"
ElseIf location = "NY" Then
ActiveWorkbook.SaveAs FileName:="W:\Audits\2016\NY\" & FileName1 & "-" & "checklist" & ".xlsm"
Else
ActiveWorkbook.SaveAs FileName:="W:\Audits\2016\Atlanta\" & FileName1 & "-" & "checklist" & ".xlsm"
End If
而是使用:
Dim myYear as String, locations() as String, locationForPath as String
Dim locCounter as Long
myYear = ThisWorkbook.Worksheets("Sheet1").Range("a2").value2 'the cell with year value, for example 2016
locations = Split("Illinois,LA,NY",",")
For locCounter = LBound(locations) to UBound(locations)
If location = locations(locCounter) Then locationForPath = location: Exit For
Next locCounter
If locationForPath = vbNullString Then locationForPath = "Atlanta"
ActiveWorkbook.SaveAs FileName:="W:\Audits\" & myYear & "\" & locationForPath & "\" & FileName1 & "-" & "checklist" & ".xlsm"