2009-11-15 144 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