2011-07-26 42 views
1

我有一個Excel宏,它將複製特定工作表中的所有信息並將其複製到新的工作簿中。代碼如下:Excel宏:爲什麼這不會保存在正確的目錄中?

Option Explicit 

Sub TwoSheetsAndYourOut() 
Dim NewName As String 
Dim nm As Name 
Dim ws As Worksheet 

If MsgBox("Copy specific sheets to a new workbook" & vbCr & _ 
"New sheets will be pasted as values, named ranges removed" _ 
, vbYesNo, "New Copy") = vbNo Then Exit Sub 

With Application 
    .ScreenUpdating = False 

    On Error GoTo ErrCatcher 
    Sheets("Input").Copy 
    On Error GoTo 0 

    For Each ws In ActiveWorkbook.Worksheets 
     ws.Cells.Copy 
     ws.[A1].PasteSpecial Paste:=xlValues 
     ws.Cells.Hyperlinks.Delete 
     Application.CutCopyMode = False 
     Cells(1, 1).Select 
     ws.Activate 
    Next ws 
    Cells(1, 1).Select 

    For Each nm In ActiveWorkbook.Names 
     nm.Delete 
    Next nm 

    NewName = InputBox("Please specify the name of your new workbook", "New Copy", "input") 

    Dim sPath As String 
    sPath = ThisWorkbook.Path 
    ActiveWorkbook.SaveCopyAs sPath & NewName + ".xls" 
    ActiveWorkbook.Close SaveChanges:=False 

    .ScreenUpdating = True 
End With 
Exit Sub 

ErrCatcher: 
    MsgBox "Specified sheets do not exist within this workbook" 
End Sub 

但是,它不會將新Excel文件保存在正確的目錄中。原來的Excel文件,包含宏的一個,是在以下目錄中(在Mac):

/應用/ WORDNET /項目

不過,我每次運行宏時,它保存新WORDNET文件夾中的Excel文件,而不是PROJECTS文件夾。

如何修改代碼以保存在正確的位置?爲什麼它不保存在原始Excel文件所在的目錄中?

回答

1
sPath = ThisWorkbook.Path 

sPath是結尾沒有(至少在Windows上)一個分隔符的路徑,所以你需要添加一個在您的腳本。在你的情況下,該文件將被保存到/Applications/WORDNET名爲"PROJECTS" & NewName

的Unix:

ActiveWorkbook.SaveCopyAs sPath & "/" & NewName + ".xls" 

的Windows:

ActiveWorkbook.SaveCopyAs sPath & "\" & NewName + ".xls" 
相關問題