2013-05-30 56 views
1
Sub GetFolderPath() 
Dim InputFolder As String 
Dim OutputFolder As String 

InputFolder = Application.GetOpenFilename("Folder, *") 
Range("C1").Select 
ActiveCell.Value = InputFolder & "\" 

End Sub 

我正在使用上面的代码尝试存储,然后粘贴另一个宏我正在运行的文件夹位置。如何在Excel VBA中存储文件夹路径

任何想法如何使它停止在文件夹级别或从最后删除文件名?

谢谢!

+0

Does [this](http://stackoverflow.com/a/5975453/1048539)适用于您正在做的事情吗? – enderland

+0

我在这里发布之前实际上已经尝试过了。当我尝试时它没有工作,但我可能做错了。 我上面发表的作品,除了它在结束时返回一个文件名而不是在文件夹级别结束。 – NPoorbaugh

回答

2

你可以使用

FileName = Dir(InputFolder) 
InputFolder = Left(InputFolder, Len(InputFolder)-Len(FileName)) 

迪尔()获取只是文件名和左()帮助减磅字符串只是文件夹路径。

+0

你甚至可以在一行内做到:)所以,两个或更多选项可用:) –

0

如果我理解正确,您希望获取文件的路径,但不想在InputFolder字符串中输入文件名。如果我理解正确的话,那么这将这样的伎俩:

Option Explicit 

Sub GetFolderPath() 
Dim InputFolder As String 
Dim OutputFolder As String 

InputFolder = Application.GetOpenFilename("Folder, *") 
Range("C1").Value = getFilePath(InputFolder) 

End Sub 

Function getFilePath(path As String) 

Dim filePath() As String 
Dim finalString As String 
Dim x As Integer 
filePath = Split(path, "\") 

For x = 0 To UBound(filePath) - 1 
    finalString = finalString & filePath(x) & "\" 
Next 

getFilePath = finalString 
End Function 

而且,你不必为了写文件名以电子表格的另一个宏得到它。您可以从第一个宏中调用另一个宏,并将文件名作为参数传递,或者将文件名变量设置为模块级变量,以便其他宏可以访问它(假设第二个宏位于同一个模块中)。

+0

完美,谢谢! – NPoorbaugh

+0

很高兴能帮到你!确保标记您的答案,以便其他访问者在遇到此问题时能找到有效的答案。 – Casey

+1

这似乎很多工作来创建文件夹路径的数组只是为了修剪文件名。我会看看我发布的解决方案,因为它只使用两行,运行速度更快。 – AxGryndr

1

甚至有更短的选择让你的路径。只是一个单行:

'...your code 
Dim InputFolder As String 
InputFolder = Application.GetOpenFilename("Folder, *") 

'new, single line solution 
InputFolder = Mid(InputFolder, 1, InStrRev(InputFolder, Application.PathSeparator)) 

我想可能有一些可用的更多的选择:)

0

哇,这款主板是不可思议!我会使用casey的代码,它完美的工作:)。我还添加了一个功能来根据需要创建子文件夹。

这是我最终决定的产品。

Option Explicit 

Sub GetFolderPath() 
Dim InputFolder As String 
Dim OutputFolder As String 

MsgBox ("Please Select the Folder of Origin") 
    InputFolder = Application.GetOpenFilename("Folder, *") 
    Range("D5").Value = getFilePath(InputFolder) 
MsgBox ("Please Select the Desired Destination Root Folder") 
    InputFolder = Application.GetOpenFilename("Folder, *") 
    Range("E5").Value = getFilePath(InputFolder) 

    Dim OutputSubFolder As String 
    Dim Cell As Range 
     Range("E5").Select 
    OutputSubFolder = ActiveCell.Value 


    'Loop through this range which includes the needed subfolders 
     Range("C5:C100000").Select 
      For Each Cell In Selection 
     On Error Resume Next 
      MkDir OutputSubFolder & Cell 
     On Error GoTo 0 
     Next Cell 

End Sub 

Function getFilePath(path As String) 

Dim filePath() As String 
Dim finalString As String 
Dim x As Integer 
filePath = Split(path, "\") 

For x = 0 To UBound(filePath) - 1 
    finalString = finalString & filePath(x) & "\" 
Next 

getFilePath = finalString 
End Function 
相关问题