如何在文本文件中提取路径并在VBA中使用它?

时间:2016-05-10 09:25:43

标签: excel vba excel-vba tex

作为初学者,我已经解决了这个问题2天,我非常渴望得到你的帮助。

我的文字文件是:

C:\Sourcefile\imported
C:\Destination\not imported
C:\Testexcel\test.xlxs

我需要阅读文本并在vba中使用这些路径。 vba代码的目标是创建一个新文件夹,如果它不在目的地中存在。

FSO = CreateObject("Scripting.FileSystemObject")
set oSourceFolder=FSO.getfolder(Line1,Readline)  'if i replace line with the path it will work
set oSourceFolder=FSO.getfolder(Line2,Readline)
set oSourceFolder=FSO.getfolder(Line3,Readline)

if dir("C:\Destination\not imported",16)="" Then Mkdir (":\Destination\not imported")

在这里,我想用线替换路径,但它不起作用。

你能帮我吗?

1 个答案:

答案 0 :(得分:0)

你必须

  • 开头添加Set关键字

FSO = CreateObject("Scripting.FileSystemObject"

  • 使用ReadLine对象的TextStream方法将文本文件的每一行检索到string对象

  • 解析为string返回的可能的文件规范并仅获取其路径部分

  • 使用FileSystemObject对象的FolderExists方法检查现有文件夹

  • 最后得到(如果存在)该文件夹或通过FileSystemObject对象的GetFolderCreateFolder方法创建(如果不存在)

非常类似:

     Option Explicit

     Sub main()
        Dim FSO As FileSystemObject
        Dim foldersListFile As TextStream
        Dim folderName As String
        Dim oSourceFolder As Folder

        Set FSO = CreateObject("Scripting.FileSystemObject")

        Set foldersListFile = FSO.OpenTextFile("C:\myPath\folders.txt", ForReading, TristateFalse)

        Do While Not foldersListFile.AtEndOfStream
             folderName = GetFolderStringOnly(foldersListFile.ReadLine)

             If FSO.FolderExists(folderName) Then
                 Set oSourceFolder = FSO.GetFolder(folderName)
             Else
                 Set oSourceFolder = FSO.CreateFolder(folderName)
             End If
           Loop

        foldersListFile.Close

     End Sub

     Function GetFolderStringOnly(textLine As String) As String
         Dim iDot As Long, iSlash As Long
         iDot = InStrRev(textLine, ".")
         If iDot > 0 Then
             iSlash = InStrRev(Left(textLine, iDot), "\")
             textLine = Left(textLine, iSlash - 1)
         End If
         GetFolderStringOnly = textLine
     End Function