繁体   English   中英

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

[英]How to extract a path in text file and use it in VBA?

作为一个初学者,我已经遇到这个问题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")

在这里,我想用行替换路径,但是行不通。

你能帮我吗 ?

你必须

  • 在开头添加Set关键字

FSO = CreateObject("Scripting.FileSystemObject"

  • 使用TextStream对象的ReadLine方法将文本文件的每一行都检索到一个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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM