2013-10-06 83 views
0

問題是: 我需要比較FOLDER1路徑和FOLDER2 VBS中的路徑字符串。需要比較VBS中的文件夾路徑(.regex)

FOLDER1我從文本文件中讀取,它之前保存過。 FOLDER2 - 從選擇文件夾對話框。 我想阻止用戶選擇FOLDER2如果:
FOLDER2 = FOLDER1 FOLDER2 = FOLDER1\some_folder FOLDER2 = Parent_Folder\FOLDER1

例如: Folder1 = c:\users\user\Documents 然後Folder2不能:c:\users\user\Documentsc:\users\user\Documents\Lettersc:\users\user\

不能做出正確的正則表達式來進行比較。現在使用下面的代碼,但需要正常的解決方案。

RightPath = 0 
    Do 

    Set objShell = CreateObject("Shell.Application") 
    Set objFolder = objShell.BrowseForFolder(0, "Select folder:", &H10&, strPath) 

     If objFolder Is Nothing Then 
     msgbox "Configuration canceled" ,64 , "Information" 
     Wscript.Quit 
    End If 

    Set objFolderItem = objFolder.Self 
    objPath = objFolderItem.Path 

    ' Right now, Check for users folder only 
    RightPath = RightPath + 1 
    Dim re, targetString 
    Set re = New RegExp 
    With re 
     .Pattern = "Desktop|Documents|Downloads|Music|Pictures|Videos" 
     .Global = False 
     .IgnoreCase = True 
    End With 

    targetString = objPath 
    If re.Test(targetString) Then 
     msgbox "You cannot choose:" & vbCrLf & vbCrLf & _ 
     "Desktop, Documents, Downloads, Music, Pictures or Videos" & vbCrLf & vbCrLf & _ 
    "Please select another location" ,48 , "Warning!" 
     RightPath = 0 
    End If 

    Loop Until RightPath > 0 

    msgbox "You selected "+targetString ,0 , "Information," 
    Wscript.Quit 

回答

0

如果它不能被任何一項:c:\users\user\Documents, c:\users\user\Documents\Lettersc:\users\user\然後Instr可能與前兩者有所幫助。

例如,

Folder1 = "c:\users\user\Documents" 
Folder2 = "c:\users\user\Documents\Letters" 
If InStr(Folder2,Folder1) Then FAIL 

如果你不想讓用戶輸入的任何部分是相同的Folder1中,那麼你可以扭轉InStr檢查的順序。

如果您需要比這更具體,可能需要將文件夾字符串拆分爲數組(由「\」分割),然後比較數組中的前x個字段。

+0

是的。謝謝。 InStr的作品。 – MVKozyrev

0

我打算假定只應排除直接的父文件夾和子文件夾(例如FOLDER1\foo被禁止,但允許FOLDER1\foo\bar)。如果這種假設是正確的,這樣的事情應該工作:

Set fso = CreateObject("Scripting.FileSystemObject") 
Set app = CreateObject("Shell.Application") 

dir1 = LCase(fso.GetAbsolutePathName("C:\Users\user")) 
parent1 = fso.GetParentFolderName(dir1) 

Do 
    Set fldr = app.BrowseForFolder(0, "Select folder:", &H10&, dir1) 
    If fldr Is Nothing Then Exit Do 'user pressed [Cancel] 

    dir2 = LCase(fldr.Self.Path) 
    parent2 = fso.GetParentFolderName(dir2) 
Loop Until dir1 <> dir2 And parent1 <> dir2 And dir1 <> parent2 

注意與你使用BrowseForFolder的參數,用戶將只能選擇以下dir1一個文件夾,除非他種不同的路徑進入輸入字段。