在vba中选择正确的文件夹

时间:2016-11-07 22:15:31

标签: excel vba excel-vba

我写了一个宏,询问您使用消息框保存工作表的所有图形的文件夹,但是在图像中保存的不是所需的文件夹,而是保存在父文件夹中。

例如,它不是保存在C:\ parent \ desiredFolder中,而是保存在C:\ parent \

感谢您的帮助。

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 个答案:

答案 0 :(得分: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 :(得分:1)

您不会在导出图表的循环中使用变量fldr ...