【问题标题】:Setting variable to subfolder name based on user selection根据用户选择将变量设置为子文件夹名称
【发布时间】:2019-05-06 09:41:50
【问题描述】:

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

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

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 部分并将其存储为变量

【问题讨论】:

标签: excel vba


【解决方案1】:

好的,所以你想为 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

【讨论】:

  • 嗨,我更新了我的问题,因为我意识到该文件位于子文件夹中。我尝试了您的代码,但它返回了整个文件路径,我认为这是因为该文件位于文件夹内文件夹内的文件夹内(如果有意义的话)。你知道如何解决这个问题
  • 根据您的需要更新了我的答案。如果有帮助,请标记为答案。
  • 嗯,它仍然返回整个文件路径
  • folder name of the file locationmain folder where the file is located 是什么意思。请发布路径名称以及您要返回的内容。
  • 这是文件路径 C:\Store Location\Employees\Contact Information\Phone Numbers\11373,我只想提取 11373 部分并将其存储为变量
猜你喜欢
  • 2019-06-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-05-29
  • 2020-12-06
  • 2016-09-11
  • 1970-01-01
相关资源
最近更新 更多