首页 > 解决方案 > 根据用户选择将变量设置为子文件夹名称

问题描述

我的代码提示用户选择一个文件。我想将变量设置为文件位置的文件夹名称,但文件位于子文件夹中。

我有这个代码来打开文件。

fileAndPath = Application.GetOpenFilename(FileFilter:="Excel Files (*.csv), _ 
*.csv", Title:="Select a file")
If fileAndPath = False Then Exit Sub

这是文件路径 C:\Store Location\Employees\Contact Information\Phone Numbers\11373

我想提取 11373 部分并将其存储为变量

标签: excelvba

解决方案


好的,所以你想为 getOpenFileName 设置一个默认文件夹。在 getOpenFileName 之前加上ChDir "D:\Test". 如果驱动器不是 C:,则在 ChDir 前面加上 ChDrive "DriveLetter:"

Sub test()
ChDrive "D:"
Application.DefaultFilePath = "D:\Test"

fileAndPath = Application.GetOpenFilename(FileFilter:="Excel Files (*.csv),*.csv", Title:="Select a file")
If fileAndPath = False Then
Exit Sub
End If
folderPath = Left(fileAndPath, InStrRev(fileAndPath, "\") - 1)
MsgBox (Mid(folderPath, InStrRev(folderPath, "\") + 1))
End Sub

推荐阅读