Reputation: 11982
Using VB6
In a folder, am having n number of text files, file names are like abc.mis-.txt, [email protected], so i want to rename the filenames like abcmis.txt, deffin.txt. I used a function for renaming.
Code
Dim filename3 As String
filename3 = Dir$(txtSourceDatabaseFile & "\*.txt", vbDirectory)
Do While filename3 <> ""
'Function for renaming
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
Above Coding is working, the problem is am using while conditon, so it will rename all the txt files, It is giving a names likes
For Example.
The first time giving a fileaname as abc in "stroutput"
The second time giving a filename as abcdef in "Stroutput"
...,
It is adding a previous filename also, because am getting a filename in while loop itself.
How to modify my code.
Upvotes: 1
Views: 82
Reputation: 12538
Move your function into a VB6 function that takes the filename as an argument and returns the new one, eg :
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
Then use something like this this to get the new filename :
Do While filename3 <> ""
strNewName = GetTextOnlyFileName(strFileName3)
'next rename the file to strNewName
'get name of next file
Loop
However, what do you want to happen if two different source filenames give the same renamed one? Eg, currently [email protected] and ab@[email protected] would return the same thing.
Your code is currently appending the filename to the previous one because you're reusing the same variables again and again in your loop without clearing the prior values. My function will work, but you could just add the line strOutPut = "" after the line strInput = filename3 and that should work too.
Upvotes: 1