VBA Excel获取文件path – 无法正常工作

我一直在使用下面的代码在Excel中指定一个文件夹path:

Set diaFolder = Application.FileDialog(msoFileDialogFolderPicker) diaFolder.AllowMultiSelect = False diaFolder.Show 

我会出口pdf文件(通过VBA代码)到该path。 当我在Windows XP上运行Excel 2007时,此代码完美无瑕。 我最近升级了我的操作系统和办公版本,现在我的Excel 2010在Windows 7上运行。代码不再像以前那样工作,问题是每次运行代码时,path都会一直向上移动一个级别。

例如,假设我select以下path:

\users\AK\Desktop\Projects\ProjectM

实际的pdfs保存在\users\AK\Desktop\Projects\

如果我select: \users\AK\Desktop\Projects\ pdfs保存在\users\AK\Desktop\

如果我继续运行代码,它会一直跳到一个级别,所以可以说我连续运行3次(每次没有select我的path),我的pdf文件将存储在:\ users \ AK \

我不知道它是一个Excel 2010问题还是Windows 7问题。 有没有人遇到过?

编辑:完整的代码包括:

 Private Sub CODERUN() ' Define values FN_A = Cells(2, 2).Value ' Print PDF version Set diaFolder = Application.FileDialog(msoFileDialogFolderPicker) diaFolder.AllowMultiSelect = False diaFolder.Show ' Print PDF version Sheets("Part A").Select ActiveSheet.ExportAsFixedFormat Type:=xlTypePDF, filename:=FN_A & "_A", _ Quality:=xlQualityStandard, _ IncludeDocProperties:=True, _ IgnorePrintAreas:=False, _ OpenAfterPublish:=False End Sub 

我明白你在问什么,因为我碰到了同样的问题。 我相信你的问题是,如果你运行你有的代码,然后在对话框中点击取消或确定,下一次运行代码时,初始path与上一个初始path相比是高一级的。 发生这种情况的原因是因为对话框不放在尾部\然后截断到下一个\的path。 因此,每次使用对话框时,都会在path中失去一个级别。

下面的代码应该为你工作,你可以接受或取消,直到你的心是内容没有初始目录改变。

 Private Sub CODERUN() Dim sFilePath as String ' Define values FN_A = Cells(2, 2).Value ' Print PDF version With Application.FileDialog(msoFileDialogFolderPicker) .AllowMultiSelect = False If .Show = -1 Then sFilePath = .SelectedItems(1) & "\" .InitialFileName = sFilePath '<--Remove this line to see the problem End If End With ' Print PDF version Sheets("Part A").ExportAsFixedFormat Type:=xlTypePDF, filename:=sFilePath & FN_A & "_A", _ Quality:=xlQualityStandard, _ IncludeDocProperties:=True, _ IgnorePrintAreas:=False, _ OpenAfterPublish:=False End Sub