2009-10-19 58 views
0

使用VB6替換文件名的問題?

在文件夾中,我有n個文本文件,文件名像abc.mis-.txt,def.fin @ .txt,所以我想重命名文件名,如abcmis.txt, deffin.txt。我使用了重命名功能。

代碼

Dim filename3 As String 
filename3 = Dir$(txtSourceDatabaseFile & "\*.txt", vbDirectory) 
Do While filename3 <> "" 

「重命名

Dim strInput As String 
Dim stroutput As String 
Dim strChar As String 
Dim intChar As Integer 
Dim intLoop As Integer 
strInput = filename3 
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 & "\" & filename3 As txtSourceDatabaseFile & "\" & stroutput & ".txt" 


filename3 = Dir$ 
Loop 

以上編碼功能工作,問題是用我同時conditon,所以它會重新命名所有的txt文件,這是給一個名字喜歡

例如。

The first time giving a fileaname as abc in "stroutput" 
The second time giving a filename as abcdef in "Stroutput" 
..., 

它也添加了一個以前的文件名,因爲我正在while循環中獲取一個文件名。

如何修改我的代碼。

回答

1

將你的函數到VB6的函數,它的文件名作爲參數,並返回新的一個,如:

Private Function GetTextOnlyFileName(ByVal strOldName as String) As String 
    Dim strTemp As String 
    Dim strChar As String 
    Dim intChar As Integer 
    Dim intLoop As Integer 
    For intLoop = 1 To Len(strOldName) 
     strChar = Mid$(strOldName, 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 
     strTemp = strTemp & strChar 
     End If 
    Next 
    GetTextOnlyFileName = strTemp 
End Function 

然後使用這樣這個東西來獲得新的文件名:

Do While filename3 <> "" 
    strNewName = GetTextOnlyFileName(strFileName3) 
    'next rename the file to strNewName 


    'get name of next file 
Loop 

但是,如果兩個不同的源文件名給出相同的重命名文件名,您希望發生什麼?例如,目前[email protected]和ab @ cd @ ef.txt會返回相同的結果。

您的代碼當前正在將文件名追加到前一個,因爲您在循環中一次又一次重複使用相同的變量而不清除先前的值。我的函數可以工作,但是你可以在strInput = filename3這行之後加上strOutPut =「」這行,這也可以。