2014-09-05 82 views
-1

好吧,就像許多其他人一樣,我是VB腳本的noob。我想要做的是創建一個VB腳本,它將操縱從Fulton A1032-CCC Adamsville到A1032-CCC的文件名。我瀏覽過很多網站試圖找到答案,但只有在中途工作時才提出來。VB腳本,將操縱文件名

strComputer = "." 

Set objWMIService = GetObject("winmgmts:\\" & strComputer & "\root\cimv2") 

Set colFiles = objWMIService.ExecQuery _ 
("ASSOCIATORS OF {Win32_Directory.Name='H:\Darrell 2014 folder\Distview Wiki Revamp\To'} Where " _ 
    & "ResultClass = CIM_DataFile") 

For Each objFile In colFiles 
    strPath = objFile.Drive & objFile.Path 
    strExtension = objFile.Extension 
    strFileName = objFile.FileName 

    If Left(strFileName, 7) = "Fulton " Then 
     intLength = Len(strFileName) 
     strFileName = Right(strFileName, intLength - 7) 
    End If 

    If Right(strFileName, 10) = " Adamsville" Then 
     intLength = Len(strFileName) 
     strFileName = Left(strFileName, intLength - 10) 
    End If 

    strNewName = strPath & strFileName & "." & strExtension 
    errResult = objFile.Rename(strNewName) 
Next 

請幫助

+1

VBScript!= VB.Net!= VB6。 IOW,它們不是同義詞 - 它們是三種不同的語言。請僅使用** **相關標籤(本例中爲'vbscript')。謝謝。 – 2014-09-05 15:54:25

回答

-2

學習計數:

>> WScript.Echo Len(" Adamsville") 
>> 
11 
>> 

或寫一個函數:

>> Function endsWith(b, t) 
>> endsWith = Right(b, len(t)) = t 
>> End Function 
>> WScript.Echo CStr(endsWith("Fulton A1032-CCC Adamsville", " Adamsville")) 
>> 
True 

更新WRT downvotes:

隨着downvotes表明,至少有兩個人誰也不能指望兩種:

Option Explicit 

Function qq(s) : qq = """" & s & """" : End Function 

Dim strFileName : strFileName = "Fulton A1032-CCC Adamsville" 
Dim intLength 
WScript.Echo 0, qq(strFileName) 

' assume the structure of the input data is: 
' <todelete+blank><tokeep><blank+todelete> 
WScript.Echo 1, qq(Split(strFileName)(1)) 

' the ot's code 'works' if you count correctly 
If Left(strFileName, 7) = "Fulton " Then 
    intLength = Len(strFileName) 
    strFileName = Right(strFileName, intLength - 7) 
End If 
If Right(strFileName, 11) = " Adamsville" Then 
    intLength = Len(strFileName) 
    strFileName = Left(strFileName, intLength - 11) 
End If 
WScript.Echo 2, qq(strFileName) 

輸出:

cscript 25689666.vbs 
0 "Fulton A1032-CCC Adamsville" 
1 "A1032-CCC" 
2 "A1032-CCC" 
+0

你會如何處理文件名前後各種數量的字符。中間將是相同數量的字符。 – 2014-09-08 17:28:07

1

爲什麼不直接用替換功能呢?例如:

Dim fileName As String 

fileName = "Fulton A1032-CCC Adamsville" 

fileName = Replace(fileName, "Fulton ", "") 
fileName = Replace(fileName, " Adamsville", "") 

MsgBox fileName 

輸出是A1032-CCC。如果搜索字符串中的任何一個或兩個都不存在,這也適用。