如何在文本文件中提取路径并在VBA中使用它?
作为一个初学者,我已经与这个问题2天,我很渴望你的帮助。如何在文本文件中提取路径并在VBA中使用它?
我的文本文件是:
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")
在这里,我想用行替换路径,但它不工作。
你能帮助我吗?
必须
- 在
FSO = CreateObject("Scripting.FileSystemObject"
开始)
使用方法对象TextStreamReadLine检索文本文件的每一行进入加
Set
关键字astring
对象解析
string
返回可能的文件规范并只获得他们的路径部分使用FileSystemObject对象的FolderExists方法来检查现有的文件夹
终于搞定(如果存在的话),其文件夹或创建(如果不存在)它通过GetFolder或CreateFolder FileSystemObject对象的方法
很想如下:
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
我只想问你,我如何指定vba将读取哪一行来提取txt文件的路径?谢谢 – mitsuki
你可以计算'Do While - Loop'模块中的行数,并在到达想要的行时停止。要在开始时添加一些“Dim countLine as long”,并在循环内添加一个“countLine = countLine + 1” – user3598756
您是否通过了? – user3598756
FSO.FolderExists和FSO.CreateFolder会有所帮助。设置一个文件对象,然后从该对象获取路径也可能有所帮助。 –
@Nathan_Sav是的,但我没有在那个问题,问题是,我不知道如何使用文本文件,它有路径vba – mitsuki
也检查此链接.. http://www.rondebruin.nl/ win/s9/win003.htm – Sixthsense