简体   繁体   English

在VBS中使用循环重命名文件

[英]Using a loop in VBS to rename a file

I have a script already which can perform a saveas routine for file names that begin with certain characters. 我已经有一个脚本,可以对以某些字符开头的文件名执行saveas例程。

This is the script below. 这是下面的脚本。

        'launch Excel and open file
Const xlExcel8          = 56
Const xlOpenXMLWorkbook = 51
Set fso   = CreateObject("Scripting.FileSystemObject")
Set xlObj = CreateObject("Excel.Application")


Set re = New RegExp
re.Pattern = "^ABC.*\.xlsx$"
re.IgnoreCase = True

For Each f In fso.GetFolder("C:\Users\Jimbo\Documents\_ThisWeek").Files
  If re.Test(f.Name) Then
    Set xlFile = xlObj.WorkBooks.Open(f.Path)
    xlObj.DisplayAlerts = False
        xlfile.SaveAs "C:\Users\Jimbo\Documents\_ThisWeek\Weekly Feed File.xls", xlExcel8

xlFile.Close True


End If
xlObj.DisplayAlerts = True
Next

Set re = New RegExp
re.Pattern = "^ABC.*\.xlsx$"
re.IgnoreCase = True

For Each f In fso.GetFolder("C:\Users\Jimbo\Documents\_ThisWeek").Files
  If re.Test(f.Name) Then
    fso.Deletefile(f.Path)
End If

Next 


xlObj.Quit

Can anyone pls assist with updating the script to rename a file instead of performing a saveas? 任何人都可以协助更新脚本以重命名文件而不是执行另存为吗?

This is an extremely simple example. 这是一个非常简单的例子。

I don't have enough to go on for how you want to rename the file so you need to fill in that logic. 我还没有足够的方法来重命名文件,因此您需要填写该逻辑。 I just defined a variable strName that holds a string value for an example. 我刚刚定义了一个变量strName ,它包含一个字符串值作为示例。

You would want to set strName inside the If statement to something that works for you and changes on each loop. 您可能希望将If语句中的strName设置为适合您的内容,并在每个循环中进行更改。

If the path or name will be complex, make sure you double quote the variable. 如果路径或名称很复杂,请确保将变量用双引号引起来。

'rename files from one folder to another
option explicit
Dim fso:      Set fso = CreateObject("Scripting.FileSystemObject")
Dim strPath:  strPath = "C:\Users\Jimbo\Documents\_AnotherFolder\"
Dim strName:  strName = "SetYourNameHere.xls"
Dim re:       Set re = New RegExp
Dim oFile

re.Pattern = "^ABC.*\.xlsx$"
re.IgnoreCase = True

For Each oFile In fso.GetFolder("C:\Users\Jimbo\Documents\_ThisWeek").Files
    If re.Test(oFile.Name) Then
        oFile.move strPath
        oFile.name = strName
    End If
Next

You already have the file object. 您已经有了文件对象。 Just move it with it's own method to your other folder then use it's name property to set the value to what you want the name to be. 只需使用它自己的方法将其移动到其他文件夹,然后使用其name属性将值设置为您想要的名称即可。

You should add verification that the file doesn't already exist in the folder and handle that situation gracefully. 您应该添加验证,以确保该文件在文件夹中不存在,并妥善处理该情况。

You can rename a file by using the MoveFile Method 您可以使用MoveFile方法重命名文件

Dim Fso
Set Fso = WScript.CreateObject("Scripting.FileSystemObject")
Fso.MoveFile "Test.txt", "Test2.txt"

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM