2009-11-15 104 views
0

我使用VB6,我有一個文件夾,我有n文件數。我想將文件擴展名更改爲.txt。我使用下面的代碼將所有.fin文件的擴展名更改爲.txt文件重命名問題?

Dim filename1 As String 
filename1 = Dir$(txtsourcedatabasefile & "\*.fin", vbDirectory) 
Do While filename1 <> "" 
    Dim strInput As String 
    Dim strOutput As String 
    Dim strChar As String 
    Dim intChar As Integer 
    Dim intLoop As Integer 
    strInput = filename1 
    strOutput = "" 
    For intLoop = 1 To Len(strInput) 
     strChar = Mid$(strInput, intLoop, 1) 
     intChar = Asc(strChar) 
     If ((intChar >= 48) And (intChar <= 57)) Or _ 
      ((intChar >= 65) And (intChar <= 90)) Or _ 
      ((intChar >= 97) And (intChar <= 122)) Or _ 
      (intChar = 95) Then 

      strOutput = strOutput & strChar 
     End If 
    Next 
    Name txtsourcedatabasefile & "\" & filename1 As txtsourcedatabasefile & "\" & strOutput & ".txt" 
    filename1 = Dir$ 
Loop 

上面的代碼工作用於改變.fin.txt,但與文件名而沒有任何擴展名,像Clockings2.mis04062009 022511 PMSilver_421_export等,不變換爲.txt推廣。例如,Clockings2mis04062009022511PM.txt,Silver_421_export.txt

我該如何更改此代碼?

回答

3

如果我正確地解釋你的問題,你想通過在一個目錄中的文件進行迭代和更改所有的文件擴展名爲「.fin」,或根本沒有擴展,以名爲「.txt」。您可以添加對Microsoft腳本運行時的引用,並使用FileSystemObject輕鬆完成此操作。在這個例子中,我們假設txtsourcedatabase包含要處理的目錄:

Dim fso As New FileSystemObject 
Dim fil As Variant 

For Each fil In fso.GetFolder(txtsourcedatabase).Files 
    If (LCase$(fso.GetExtensionName(fil.Name)) = "fin") Or _ 
     (fso.GetExtensionName(fil.Name) = vbNullString) Then 
    fso.MoveFile fil.Path, fso.BuildPath(fso.GetParentFolderName(fil.Path), _ 
     fso.GetBaseName(fil.Path) & ".txt") 
    End If 
Next 
-1

好了,幾件事情。這並不能真正解決你的問題,但只是你知道,你正在嘗試做的一些事情可以通過命令提示符(ren * .fin * .txt)來完成。顯然,這並沒有解決沒有擴展名的文件的問題。
其次,根據用* .fin調用Dir命令,你甚至不應該得到沒有擴展名的文件。
第三,假設你的標準是重命名所有文件.fin結束或沒有擴展名爲.txt ...這應該工作:

Private Const txtsourcedatabasefile As String = "C:\test\" 
Public Sub Example() 
    Dim filename1 As String 
    Dim strOutput As String 
    filename1 = Dir$(txtsourcedatabasefile & "*") 
    Do While LenB(filename1) 
     strOutput = filename1 
     If InStrB(1, strOutput, ".", vbBinaryCompare) = 0& Then 
      strOutput = strOutput & ".txt" 
      Name txtsourcedatabasefile & filename1 As txtsourcedatabasefile & strOutput 
     ElseIf LCase$(Right$(filename1, 4)) = ".fin" Then 
      Mid$(strOutput, Len(filename1) - 2) = "txt" 
      Name txtsourcedatabasefile & filename1 As txtsourcedatabasefile & strOutput 
     Else 
      Debug.Print "Skipped:", strOutput 
     End If 
     filename1 = Dir$ 
    Loop 
End Sub 
+0

爲什麼這會被投票? – Oorang 2009-11-18 17:05:23

0

首先,我想你想改變你的vbDirectory DIR $屬性到vbNormal。第二我認爲你應該簡化你的重命名代碼。你可以使用內置的VB函數替換來做你想做的事情。

Dim filename1 As String 

filename1 = Dir$(txtsourcedatabasefile & "\*.fin", vbNormal) 

Do While Len(filename1) > 0 
    Name txtsourcedatabasefile & "\" & filename1 As txtsourcedatabasefile & "\" & _ 
     Replace(filename1, ".fin", ".txt", Len(txtsourcedatabasefile & "\" & filename1) - 4, 1, vbTextCompare) 
    filename1 = Dir$ 
Loop