如何在VBA中更改工作簿的文件path?

所以我有一个正在保存的工作簿。 它被保存在一个名字不同的工作簿中的两个单元格中。 截至目前,它会自动保存到我的电脑上的文档文件夹。 我想将其更改为我select的文件夹。 我猜这应该是非常直接的。 这是我的代码到目前为止:

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 

谢谢!

 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 

你的问题是,默认的文件夹不是你想要保存这个文件的地方。 您可以从主菜单或代码中更改此设置:

 Application.DefaultFilePath = "H:\Projects\" 

但是…您的系统安全设置或“漫游configuration文件”可能不会让您这样做,命令将失败默默。 更糟糕的是,您可能会这样做,并在您自己的PC上成功,并将其传递给具有不同configuration的工作站的用户。

最好明确指定path:

 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 

总是检查你的文件夹path上是否有'\'反斜杠:这是一个非常常见的错误。