用VB实现文件改名

发表于:2007-07-14来源:作者:点击数: 标签:
方法一 name 重新命名一个文件、目录、或文件夹。 语法: name oldpathname as newpathname Name语句重新命名文件并将其移动到一个不同的目录或文件夹中。如有必要,Name可跨驱动器移动文件。但当newpathname和oldpathname都在相同的驱动器中时,只能重新命
方法一

name
重新命名一个文件、目录、或文件夹。
语法:
name oldpathname as newpathname

Name语句重新命名文件并将其移动到一个不同的目录或文件夹中。如有必要,Name可跨驱动器移动文件。但当newpathname和oldpathname都在相同的驱动器中时,只能重新命名已经存在的目录或文件夹。Name不能创建新文件、目录或文件夹。在一个已打开的文件上使用Name,将会产生错误。必须在改变名称之前,先关闭打开的文件。Name参数不能包括多字符(*)和单字符(?)的通配符。

示例本示例使用Name语句来更改文件的名称。示例中假设所有使用到的目录或文件夹都已存在。在Macintosh中,默认驱动器名称是C, imOldName,NewNameOldName="OLDFILE":NewName="NEWFILE"注释:定义文件名。NameOldNameAsNewName注释:更改文件名。OldName="C:\MYDIR\OLDFILE":NewName="C:\YOURDIR\NEWFILE"NameOldNameAsNewName注释:更改文件名,并移动文件。
★★★★★★★★★★★★★★★★★★★★★★★★★★

方法二
Option Explicit

注释: // Shell File Operations

Const FO_MOVE = &H1
Const FO_COPY = &H2
Const FO_DELETE = &H3
Const FO_RENAME = &H4
Const FOF_MULTIDESTFILES = &H1
Const FOF_CONFIRMMOUSE = &H2
Const FOF_SILENT = &H4 注释: don注释:t create progress/report
Const FOF_RENAMEONCOLLISION = &H8
Const FOF_NOCONFIRMATION = &H10 注释: Don注释:t prompt the user.
Const FOF_WANTMAPPINGHANDLE = &H20 注释: Fill in SHFILEOPSTRUCT.hNameMappings
注释: Must be freed using SHFreeNameMappings
Const FOF_ALLOWUNDO = &H40
Const FOF_FILESONLY = &H80 注释: on *.*, do only files
Const FOF_SIMPLEPROGRESS = &H100 注释: means don注释:t show names of files
Const FOF_NOCONFIRMMKDIR = &H200 注释: don注释:t confirm making any needed dirs

Const PO_DELETE = &H13 注释: printer is being deleted
Const PO_RENAME = &H14 注释: printer is being renamed
Const PO_PORTCHANGE = &H20 注释: port this printer connected to is being changed
注释: if this id is set, the strings received by
注释: the copyhook are a doubly-null terminated
注释: list of strings. The first is the printer
注释: name and the second is the printer port.
Const PO_REN_PORT = &H34 注释: PO_RENAME and PO_PORTCHANGE at same time.


Private Type SHFILEOPSTRUCT
hwnd As Long
wFunc As Long
pFrom As String
pTo As String
fFlags As Integer
fAnyOperationsAborted As Long
hNameMappings As Long
lpszProgressTitle As String 注释: only used if FOF_SIMPLEPROGRESS
End Type


注释:Private Declare Function SHFileOperation Lib "shell32.dll" Alias " SHFileOperationA" (lpFileOp As SHFILEOPSTRUCT) As Long

Private Declare Function SHFileOperation Lib "shell32.dll" (lpFileOp As SHFILEOPSTRUCT) As Long


Private Sub Command1_Click()
Dim tud As SHFILEOPSTRUCT
Dim rc As Long
With tud
.hwnd = Me.hwnd
.pFrom = "c:\aaa.txt"
.pTo = "c:\bbb.txt"
.fFlags = FOF_ALLOWUNDO
.wFunc = FO_RENAME
End With
rc = SHFileOperation(tud)
End Sub
★★★★★★★★★★★★★★★★★★★★★★★★★★

方法三
Private Sub Command1_Click()
Dim icmd As Object
Set icmd = CreateObject("wscript.shell")
icmd.Run "command.com /c rename c:\test.txt aa.txt", 0, True
End Sub

可運行任何DOS命令,2000下需用cmd.exe 

原文转自:http://www.ltesting.net