2016-11-07 53 views
0

我寫了一個宏,詢問您使用消息框保存工作表的所有圖形的文件夾,但在和圖形不保存在所需的文件夾中,但在父一。在vba中選擇正確的文件夾

例如,而不是保存在C:\父母\ desiredFolder在C節省:\父母\

謝謝您的幫助。

Sub EXPORTCHARTS() 

MsgBox ("Seleziona la cartella dove vuoi esoportare i grafici") 

ActiveSheet.Select 
ActiveWindow.Zoom = 400 

Dim sItem As String 
Dim dlgOpenFolder As FileDialog 

Set dlgOpenFolder = Application.FileDialog(msoFileDialogFolderPicker) 
dlgOpenFolder.Filters.Clear 

With dlgOpenFolder 
    .Title = "Select a Folder" 
    .AllowMultiSelect = False 
    .InitialFileName = strPath 
    If .Show <> -1 Then GoTo NextCode 
    sItem = .SelectedItems(1) 
End With 

NextCode: 
GetFolder = sItem 
Set fldr = dlgOpenFolder 

' --------------------------------------------------------- 
Dim objCht As ChartObject 

i = 1 
For Each objCht In ActiveSheet.ChartObjects 
    objCht.Chart.Export Filename:=i & ".jpg", FilterName:="JPG" 
    i = i + 1 
Next objCht 

' --------------------------------------------------------- 
ActiveWindow.Zoom = 50 

End Sub 

回答

2

Jbjstam在他們的回答指出,當你正在保存的文件不使用文件夾名稱。

如果用戶從FileDialog中取消,則您的邏輯也出現問題,即使您在循環中正確使用了sItem,也不會設置sItem,因此文件將被保存到當前目錄。

下面應該工作:

Sub EXPORTCHARTS() 

    MsgBox ("Seleziona la cartella dove vuoi esoportare i grafici") 

    ActiveSheet.Select 
    ActiveWindow.Zoom = 400 

    Dim sItem As String 
    Dim dlgOpenFolder As FileDialog 
    Dim i As Long 

    Set dlgOpenFolder = Application.FileDialog(msoFileDialogFolderPicker) 
    dlgOpenFolder.Filters.Clear 

    With dlgOpenFolder 
     .Title = "Select a Folder" 
     .AllowMultiSelect = False 
     .InitialFileName = strPath 
     If .Show <> -1 Then 
      MsgBox "No path selected" 
      Exit Sub 
     End If 
     sItem = .SelectedItems(1) 
    End With 

    ' --------------------------------------------------------- 
    Dim objCht As ChartObject 

    i = 1 
    For Each objCht In ActiveSheet.ChartObjects 
     objCht.Chart.Export Filename:=sItem & "\" & i & ".jpg", FilterName:="JPG" 
     i = i + 1 
    Next objCht 

    ' --------------------------------------------------------- 
    ActiveWindow.Zoom = 50 
End Sub 
1

不要使用在出口排行榜循環變量FLDR ...

+0

其實'sItem'或'GetFolder'將是可能包含要使用的路徑的變量。 'fldr'只是一個指向'FileDialog'對象的指針。但潛在的問題是正確的 - 不使用用戶選擇的路徑作爲保存的一部分。 – YowE3K

+0

哦,是的!謝謝你的正確回答:-) – Jbjstam

+0

非常感謝。有用 – ilFonta