VBA里如何调用目录对话框并取得路径

 我来答
秋天的黄叶子
2010-06-16 · 超过38用户采纳过TA的回答
知道小有建树答主
回答量:112
采纳率:100%
帮助的人:86.3万
展开全部
给你一个现成的,你只需拷贝到你的宏里去使用;
Sub 查找文件夹下子文件夹及其大小()
Dim theDir As String

Set pt = ActiveSheet.Range("a1")
pt.Worksheet.Columns(1).ClearContents
theDir = Application.InputBox("输入指定文件夹的路径:", "查看子文件夹及其大小")
pt = theDir
listPath theDir

pt.Worksheet.Columns("a:b").AutoFit
End Sub

Sub listPath(strDir As String)
Dim thePath As String
Dim strSdir As String
Dim theDirs As Scripting.Folders
Dim theDir As Scripting.Folder
Dim row As Integer
Dim s As String
Dim myFso As Scripting.FileSystemObject

Set myFso = New Scripting.FileSystemObject
If Right(strDir, 1) <> "\" Then strDir = strDir & "\"
thePath = thePath & strDir

row = pt.row '此段为获取此目录下的文件名
s = Dir(thePath, 7) '获取第一个文件
Do While s <> ""
row = row + 1
Cells(row, 1) = s '文件的名称
Cells(row, 1).Font.Color = RGB(256, 12, 213)
Cells(row, 1).Font.Bold = Ture
s = Dir
Loop
Set pt = Cells(row, 1)
Set pt = pt.Offset(1, 0)
Set theDirs = myFso.getfolder(strDir).subfolders '取得所有子文件
For Each theDir In theDirs
pt = theDir.Path
pt.Next = theDir.Size
listPath theDir.Path
Next

Set myFso = Nothing
End Sub

Private Sub CommandButton1_Click()
查找文件夹下子文件夹及其大小
End Sub

参考资料: VBA,文件及文件夹目录

已赞过 已踩过<
你对这个回答的评价是?
评论 收起
yanxiong2008
2010-06-14 · TA获得超过123个赞
知道小有建树答主
回答量:88
采纳率:0%
帮助的人:96.8万
展开全部
'声明API函数
Declare Function SHBrowseForFolder Lib "shell32.dll" Alias "SHBrowseForFolderA" (lpBrowseInfo As FolderInfor) As Long
Declare Function SHGetPathFromIDList Lib "shell32.dll" Alias "SHGetPathFromIDListA" (ByVal pidl As Long, ByVal pszPath As String) As Long
Private Declare Function FindWindow Lib "user32" Alias "FindWindowA" (ByVal lpClassName As String, ByVal lpWindowName As String) As Long
Private Declare Function EnableWindow Lib "user32" (ByVal hWnd As Long, ByVal fEnable As Long) As Long
'定义变量类型
Public Type FolderInfor
hOwner As Long
pidlRoot As Long
pszDisplayName As String
lpszTitle As String
ulFlags As Long
lpfn As Long
lParam As Long
iImage As Long
End Type
Sub BrowDir()
Dim iFolder As FolderInfor
Dim pidl As Long, Flag As Long, iPath As String, Pos As Integer, myPath As String
'FindWindow取得Excel窗口的句柄
'在Excel窗口里禁止所有鼠标及键盘输入
EnableWindow FindWindow("XLMAIN", Application.Caption), False
'显示目录选择对话框
pidl = SHBrowseForFolder(iFolder)
'在Excel窗口里允许鼠标及键盘输入
EnableWindow FindWindow("XLMAIN", Application.Caption), True
iPath = Space$(512)
Flag = SHGetPathFromIDList(ByVal pidl, ByVal iPath)
If Flag Then
Pos = InStr(iPath, Chr$(0))
'取得选择的目录
myPath = Left(iPath, Pos - 1)
End If
MsgBox "你选择了 " & myPath
End Sub
本回答被提问者采纳
已赞过 已踩过<
你对这个回答的评价是?
评论 收起
coolbi5
2010-06-14 · TA获得超过1万个赞
知道大有可为答主
回答量:1.1万
采纳率:35%
帮助的人:2385万
展开全部
Option Explicit

Sub test()
MsgBox Application.ActiveWorkbook.Path
End Sub
已赞过 已踩过<
你对这个回答的评价是?
评论 收起
收起 更多回答(1)
推荐律师服务: 若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询

为你推荐:

下载百度知道APP,抢鲜体验
使用百度知道APP,立即抢鲜体验。你的手机镜头里或许有别人想知道的答案。
扫描二维码下载
×

类别

我们会通过消息、邮箱等方式尽快将举报结果通知您。

说明

0/200

提交
取消

辅 助

模 式