Excel 2010:最好使用CASE或IF来定义SAVEAS位置(VBA)
程序: Excel 2010
经验:基本
题
我想要保存我的工作簿表(和生成的.pdf)的位置依赖于单元格的值,而不是写5个子, 我想写一个使用IF
或CASE
。 我有一个静态的保存位置(保pipe箱),但我也需要保存重复在各自的单元位置。
我不能得到正确的语法来工作。
Sub saveManID() Dim sDB As String Dim sMDocs As String Dim sMBus As String Dim sName As String Dim sSel As String Dim sMan As String 'define file name sName = Sheets("Statement").Range("B52").Text 'define location name sDB = "E:\location dropbox\" sMDocs = "D:\My Documents\" sMBus = "D:\location alt\" '---- Either IF or CASE to define the SAVEAS location ----' If Sheets("Statement").Range("J2").Text = "3" Then sMan = "G:\location\folder3\" If Sheets("Statement").Range("J2").Text = "4" Then sMan = "G:\location\folder4\" '---- end ----' ActiveWorkbook.SaveAs Filename:=sMan & sName & Format(Date, "YYYYMMDD") & ".xls",_ FileFormat:=52, ReadOnlyRecommended:=False, CreateBackup:=False Sheets("Statement").Range("A1:G49").ExportAsFixedFormat Type:=xlTypePDF, Filename:=sMan & sName & ".pdf", _ Quality:=xlQualityStandard, IncludeDocProperties:=True, IgnorePrintAreas:=False, OpenAfterPublish:=True End if End if End Sub
我需要得到的Range("J2")
来定义单元格值的位置,我需要基于另一个单元格值创build名称。
如果排除IF
,Sub运行正常,但这意味着我必须重复代码并为每个值分配一个button。
澄清 – 单元格值Range("J2")
将决定文件保存到的位置,在上面的示例中,它在IF
语句中不起作用。
要修复你写的东西,试着移动你的End If
你的通用代码是这样的:
If Sheets("Statement").Range("J2").Text = "3" Then sMan = "G:\location\folder3\" End If If Sheets("Statement").Range("J2").Text = "4" Then sMan = "G:\location\folder4\" End if ActiveWorkbook.SaveAs Filename:=sMan & sName & Format(Date, "YYYYMMDD") & ".xls",_ FileFormat:=52, ReadOnlyRecommended:=False, CreateBackup:=False Sheets("Statement").Range("A1:G49").ExportAsFixedFormat Type:=xlTypePDF, Filename:=sMan & sName & ".pdf", _ Quality:=xlQualityStandard, IncludeDocProperties:=True, IgnorePrintAreas:=False, OpenAfterPublish:=True
或者像这样:
If Sheets("Statement").Range("J2").Text = "3" Then sMan = "G:\location\folder3\" ElseIf Sheets("Statement").Range("J2").Text = "4" Then sMan = "G:\location\folder4\" End if
或者像这样:
myVal = Sheets("Statement").Range("J2").Text If myVal = "3" Then sMan = "G:\location\folder3\" ElseIf myVal = "4" Then sMan = "G:\location\folder4\" End if
要使用Select Case
重新写它是这样的:
Select Case Sheets("Statement").Range("J2").Text Case "3" sMan = "G:\location\folder3\" Case "4" sMan = "G:\location\folder4\" Case Else 'set sMan to your default dropbox location here End Select