How can I change the file path of a Workbook in VB

2019-09-16 18:01发布

So I have a Workbook that is being saved. It is being saved under a name from two cells in a different workbook. As of right now, it saves automatically to the documents folder on my computer. I would like to change this to a folder of my choosing. I'm guessing this should be pretty straight-forward. Here's my code so far:

    Dim name As String

    name = Workbooks("Transfer Template").Sheets("Sheet1").Range("B1").Value & "_" & Workbooks("Transfer Template").Sheets("Sheet1").Range("B4").Value
    Windows("Protected_Form.xls").Activate
    ActiveWorkbook.SaveAs Filename:=name

Thanks!

2条回答
叛逆
2楼-- · 2019-09-16 18:41
Const MY_PATH As String = "C:\Temp\"
Dim name As String

With Workbooks("Transfer Template").Sheets("Sheet1")
    name = .Range("B1").Value & "_" & .Range("B4").Value
End With    

Workbooks("Protected_Form.xls").SaveAs Filename:= MY_PATH & name
查看更多
劫难
3楼-- · 2019-09-16 18:43

Your problem is that the default folder isn't where you want to save this file. You can change this setting from the main menu, or in code:

Application.DefaultFilePath =  "H:\Projects\"

However... Your system security settings or 'roaming profile' might not let you do this, and the command will fail silently. Worse, you might do this, and succeed on your own PC, and pass it onto a user who has a differently-configured workstation.

It's best to specify the path explicitly:

Dim wbk As Excel.Workbook
Dim strName As String
Dim strPath As String

Set wbk = Application.Workbooks("Protected_Form.xls")

With Application.Workbooks("Transfer Template").Sheets("Sheet1")
    strName = .Range("B1").Value & "_" & .Range("B4").Value
End With

strPath = "H:\Projects\"

wbk.SaveAs Filename:=strPath & strName

Always check that you have the '\' backslash on your folder path: it's a very common error.

查看更多
登录 后发表回答