Как переименовать word vba

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
Option Explicit
'Создание списка файлов в папке
Public Sub LoadFileName()    'создане списка файлов
    Dim Rng    As Range
    Dim arrPath As Variant
    Dim i      As Long
 
    On Error GoTo AddFileNewName_Err
 
    arrPath = FileDialog_(vbNullString, True, "*.*")
    If TypeName(arrPath) = "Empty" Then Exit Sub
    ActiveWorkbook.Sheets.Add After:=Sheets(Sheets.Count)
    Set Rng = ActiveSheet.Cells(1, 1)
    With Rng
        .Cells(1, 1).Value = "Директория к файлу:"
        .Cells(1, 2).Value = "Расширение файла:"
        .Cells(1, 3).Value = "Название файла:"
        .Cells(1, 4).Value = "Новое название файла:"
        For i = 1 To UBound(arrPath)
            .Cells(i + 1, 1).Value = sGetParentFolderName(arrPath(i))
            .Cells(i + 1, 2).Value = sGetExtensionName(arrPath(i))
            .Cells(i + 1, 3).Value = sGetBaseName(arrPath(i))
        Next i
        .Columns("A:D").EntireColumn.AutoFit
    End With
    Exit Sub
AddFileNewName_Err:
    MsgBox Err.Description & vbCrLf & "в VBAProject.D_Macros.LoadFileName " & vbCrLf & "в строке " & Erl, vbExclamation + vbOKOnly, "Ошибка:"
End Sub
'Переименовывание файлов по списку
Public Sub AddFileNewName()
    Dim Rng    As Range
    Dim OldFile As String, NewPathFile As String, NewPath As String, StrErr As String
    Dim i      As Long
    Dim n      As Byte
    On Error GoTo Canceled
    Set Rng = Application.InputBox(Prompt:="Выберите диапазон", Title:="Выбор диапазона:", Default:=Selection.Address, Type:=8)
    On Error GoTo AddFileNewName_Err
 
    With Rng
        If .Columns.Count <> 4 Then
            Call MsgBox("Должен быть выбран диапазон с четырьмя столбцами!", vbCritical, "Ошибка:")
            Exit Sub
        End If
        'создаю новую уникальную папку
        If .Cells(1, 1).Value = "Директория к файлу:" Then
            n = 2
        Else
            n = 1
        End If
        NewPath = .Cells(n, 1) & Application.PathSeparator & "new_" & Replace(Replace(Now(), ":", "."), " ", "_") & Application.PathSeparator
        Call MkDir(NewPath)
        'переношу и переименовую файлы
        For i = n To .Rows.Count
            If .Cells(i, 1) <> vbNullString And .Cells(i, 2) <> vbNullString And .Cells(i, 3) <> vbNullString And .Cells(i, 4) <> vbNullString Then
                OldFile = .Cells(i, 1) & Application.PathSeparator & .Cells(i, 3) & "." & .Cells(i, 2)
                NewPathFile = NewPath & .Cells(i, 4) & "." & .Cells(i, 2)
                StrErr = StrErr & MoveFile(OldFile, NewPathFile)
            Else
                StrErr = StrErr & "ошибка в данных: " & .Cells(i, 1) & " " & .Cells(i, 2) & " " & .Cells(i, 3) & " " & .Cells(i, 4) & vbNewLine
            End If
        Next i
    End With
    If StrErr <> vbNullString Then
        Call MsgBox(StrErr, vbCritical + vbOKOnly, "Ошибки:")
    Else
        Call MsgBox("Переименовывание файлов завершено!" & vbNewLine & "Создана папка с новыми файлами: " & sGetBaseName(NewPath), vbInformation + vbOKOnly, "Переименовывание файлов:")
    End If
    Exit Sub
AddFileNewName_Err:
    MsgBox Err.Description & vbCrLf & "в VBAProject.D_Macros.AddFileNewName " & vbCrLf & "в строке " & Erl, vbExclamation + vbOKOnly, "Ошибка:"
    Exit Sub
Canceled:
    Call MsgBox("Диапазон данных не выбран!", vbInformation + vbOKOnly, "Выбор диапазона:")
End Sub
 
'Файл диалог
Public Function FileDialog_(ByVal Path As String, Optional MultiSelect As Boolean = True, Optional Expansion As String = "*.xlsm") As Variant
    Dim oFd    As FileDialog
    Dim s()    As Variant
    Dim lf As Long
    Set oFd = Application.FileDialog(msoFileDialogFilePicker)
 
    With oFd    'используем короткое обращение к объекту
        .AllowMultiSelect = MultiSelect
        .Title = "Выбрать файлы"    'заголовок окна диалога
        .Filters.Clear    'очищаем установленные ранее типы файлов
        .Filters.Add "Microsoft Excel Files", Expansion, 1    'устанавливаем возможность выбора только файлов Excel
        .InitialFileName = Path    'назначаем папку отображения и имя файла по умолчанию
        .InitialView = msoFileDialogViewDetails    'вид диалогового окна(доступно 9 вариантов)
        If .Show = 0 Then
            FileDialog_ = Empty
            Exit Function    'показывает диалог
        End If
        ReDim Preserve s(1 To .SelectedItems.Count)
        For lf = 1 To .SelectedItems.Count
            s(lf) = CStr(.SelectedItems.Item(lf))    'считываем полный путь к файлу
        Next
    End With
    FileDialog_ = s
    Set oFd = Nothing
End Function
Public Function sGetParentFolderName(ByVal sPathFile As String) As String
    'sPathFile - строка, путь.
    'возвращает путь к последнему компоненту в заданном пути (его каталог).
    Dim FSO    As Object
    Set FSO = CreateObject("Scripting.FileSystemObject")
    sGetParentFolderName = FSO.GetParentFolderName(sPathFile)
    Set FSO = Nothing
End Function
 
Public Function sGetBaseName(ByVal sPathFile As String) As String
    'sPathFile - строка, путь.
    'возвращает имя (без расширения) последнего компонента в заданном пути.
    Dim FSO    As Object
    Set FSO = CreateObject("Scripting.FileSystemObject")
    sGetBaseName = FSO.GetBaseName(sPathFile)
    Set FSO = Nothing
End Function
 
Public Function sGetExtensionName(ByVal sPathFile As String) As String
    'sPathFile - строка, путь.
    'возвращает расширение последнего компонента в заданном пути.
    Dim FSO    As Object
    Set FSO = CreateObject("Scripting.FileSystemObject")
    sGetExtensionName = FSO.GetExtensionName(sPathFile)
    Set FSO = Nothing
End Function
Public Function MoveFile(OldFile As String, NewPathFile As String) As String
    'Перемещение файлов
    Dim objFSO As Object, objFile As Object
    If Dir(OldFile, 16) = vbNullString Then MoveFile = "Нет такого файла" & OldFile: Exit Function
    'перемещаем файл
    Set objFSO = CreateObject("Scripting.FileSystemObject"): Set objFile = objFSO.GetFile(OldFile)
    objFile.Copy NewPathFile
    Set objFile = Nothing: Set objFSO = Nothing
    MoveFile = vbNullString
End Function

Хитрости »

15 Август 2012              129960 просмотров


В этой статье я хотел бы рассказать как средствами VBA переименовать, переместить или скопировать файл. В принципе методы переименования, перемещения и копирования, так сказать, встроены в VBA. Это значит что можно без вызова сторонних объектов переименовать, переместить или копировать любой файл. Все это делается при помощи всего двух команд: FileCopy и Name [Исходный файл] As [Новый файл]. Притом команда FileCopy выполняет только копирование, а Name [Исходный файл] As [Новый файл] — как переименование, так и перемещение. Разница лишь в том, что при переименовании мы указываем только новое имя файла, а при перемещении — другую директорию(папку), в которую следует переместить файл. Плюс рассмотрим пример удаления файла.
Так же разберем методы копирования, перемещения, переименования и удаления файлов и папок через библиотеку FileSystemObject (FSO).

Работа с файлами встроенными командами VBA

  • Копирование файла
  • Перемещение файла
  • Переименование файла
  • Удаление файла

Работа с файлами через объект FileSystemObject (FSO)

  • Копирование файла
  • Перемещение файла
  • Переименование файла
  • Удаление файла

Работа с папками через объект FileSystemObject (FSO)

  • Копирование папки
  • Перемещение папки
  • Переименование папки
  • Удаление папки

Во всех примерах работы с файлами встроенными функциями будет присутствовать проверка на наличие файла по указанному пути. Делать это будем при помощи встроенной функции Dir([PathName],[Attributes]).
PathName — указывается полный путь к файлу
Attributes — указывается признак свойств файла. Вообще их несколько(скрытый, архивный и т.п.), но нас для наших задач будет интересовать пока только один: 16(vbDirectory). Он отвечает за проверку папок и файлов без специальных свойств(т.е. не архивные, не скрытые и т.д.). Хотя по сути его можно вообще не указывать, и тогда будет по умолчанию применен атрибут 0(vbNormal) — проверка файлов без определенных свойств. Ни в том ни в другом случае ошибкой это не будет.

Sub Copy_File()
    Dim sFileName As String, sNewFileName As String
 
    sFileName = "C:WWW.xls"    'имя файла для копирования
    sNewFileName = "D:WWW.xls"    'имя копируемого файла. Директория(в данном случае диск D) должна существовать
    If Dir(sFileName, 16) = "" Then 
        MsgBox "Нет такого файла", vbCritical, "www.excel-vba.ru"
        Exit Sub
    End If
 
    FileCopy sFileName, sNewFileName 'копируем файл
    MsgBox "Файл скопирован", vbInformation, "www.excel-vba.ru"
End Sub
Sub Move_File()
    Dim sFileName As String, sNewFileName As String
 
    sFileName = "C:WWW.xls"    'имя исходного файла
    sNewFileName = "D:WWW.xls"    'имя файла для перемещения. Директория(в данном случае диск D) должна существовать
    If Dir(sFileName, 16) = "" Then 
        MsgBox "Нет такого файла", vbCritical, "www.excel-vba.ru"
        Exit Sub
    End If
 
    Name sFileName As sNewFileName 'перемещаем файл
    MsgBox "Файл перемещен", vbInformation, "www.excel-vba.ru"
End Sub
Sub Rename_File()
    Dim sFileName As String, sNewFileName As String
 
    sFileName = "C:WWW.xls"    'имя исходного файла
    sNewFileName = "C:WWW1.xls"    'имя файла для переименования
    If Dir(sFileName, 16) = "" Then 
        MsgBox "Нет такого файла", vbCritical, "www.excel-vba.ru"
        Exit Sub
    End If
 
    Name sFileName As sNewFileName 'переименовываем файл
 
    MsgBox "Файл переименован", vbInformation, "www.excel-vba.ru"
End Sub
Sub Delete_File()
    Dim sFileName As String
 
    sFileName = "C:WWW.xls"    'имя файла для удаления
 
    If Dir(sFileName, 16) = "" Then 
        MsgBox "Нет такого файла", vbCritical, "www.excel-vba.ru"
        Exit Sub
    End If
    Kill sFileName 'удаляем файл
    MsgBox "Файл удален", vbInformation, "www.excel-vba.ru"
End Sub

Как видно ничего сложного.


Так же можно проделать те же операции с файлами при помощи объекта FileSystemObject. Строк кода несколько больше и выполняться операции будут медленнее(хотя вряд ли это будет заметно на примере одного файла). Однако есть существенный плюс — при помощи FileSystemObject можно корректно производить операции с файлами и папками на сетевом диске. Хотя та же

Dir(sFileName, 16)

часто выдает ошибку при работе с сетевыми дисками.
Прежде всего следует, я думаю, пояснить что за зверь такой — FileSystemObject.

FileSystemObject (FSO)

— содержится в библиотеке типов Scripting, расположенной в файле библиотеки scrrun.dll. Объектная модель FSO дает возможность создавать, изменять, перемещать и удалять папки и файлы, собирать о них различную информацию: имена, атрибуты, даты создания или изменения и т.д. Чтобы работать с FSO необходимо создать переменную со ссылкой на объект библиотеки. Сделать это можно двумя способами: через ранее связывание и позднее. Я не буду сейчас вдаваться в подробности этих методов — тема довольно обширная и я опишу её в другой статье.

Ранее связывание:

для начала необходимо подключить библиотеку Microsoft Scripting Runtime. Делается это в редакторе VBA: References-находите там Microsoft Scripting Runtime и подключаете. Объявлять переменную FSO при раннем связывании следует так:

Dim objFSO As New FileSystemObject

Плюсы раннего связывания: с помощью Object Browser можно просмотреть список объектов, свойств, методов, событий и констант, включенных в FSO. Но есть значительный минус: если планируется использовать программу на нескольких компьютерах, то есть большая вероятность получить ошибку(читать подробнее).
Позднее связывание: ничего нигде не надо подключать, а просто используем метод CreateObject(именно этот способ используется мной в примерах ниже). Методы таким образом просмотреть не получится, но зато работать будет без проблем на любых компьютерах без дополнительных действий.

Sub Copy_File()
    Dim objFSO As Object, objFile As Object
    Dim sFileName As String, sNewFileName As String
 
    sFileName = "C:WWW.xls"    'имя исходного файла
    sNewFileName = "D:WWW.xls"    'имя файла для переименования
    'создаем объект FileSystemObject
    Set objFSO = CreateObject("Scripting.FileSystemObject")
    'проверяем наличие файла по указанному пути
    If objFSO.FileExists(sFileName) = False Then 
        MsgBox "Нет такого файла", vbCritical, "www.excel-vba.ru"
        Exit Sub
    End If
    'копируем файл
    Set objFile = objFSO.GetFile(sFileName)
    objFile.Copy sNewFileName
 
    MsgBox "Файл скопирован", vbInformation, "www.excel-vba.ru"
End Sub
Sub Move_File()
    Dim objFSO As Object, objFile As Object
    Dim sFileName As String, sNewFileName As String
 
    sFileName = "C:WWW.xls"    'имя исходного файла
    sNewFileName = "D:WWW.xls"    'имя файла для переименования
    'создаем объект FileSystemObject    
    Set objFSO = CreateObject("Scripting.FileSystemObject")
    'проверяем наличие файла по указанному пути
    If objFSO.FileExists(sFileName) = False Then 
        MsgBox "Нет такого файла", vbCritical, "www.excel-vba.ru"
        Exit Sub
    End If
    'перемещаем файл
    Set objFile = objFSO.GetFile(sFileName)
    objFile.Move sNewFileName
    MsgBox "Файл перемещен", vbInformation, "www.excel-vba.ru"
End Sub
Sub Rename_File()
    Dim objFSO As Object, objFile As Object
    Dim sFileName As String, sNewFileName As String
 
    sFileName = "C:WWW.xls"    'имя исходного файла
    sNewFileName = "WWW1.xls"    'имя файла для переименования
    'создаем объект FileSystemObject    
    Set objFSO = CreateObject("Scripting.FileSystemObject")
    'проверяем наличие файла по указанному пути
    If objFSO.FileExists(sFileName) = False Then 
        MsgBox "Нет такого файла", vbCritical, "www.excel-vba.ru"
        Exit Sub
    End If
    'переименовываем файл
    Set objFile = objFSO.GetFile(sFileName)
    objFile.Name = sNewFileName
    MsgBox "Файл переименован", vbInformation, "www.excel-vba.ru"
End Sub

Хочу обратить внимание, что при переименовании файла через FileSystemObject необходимо указать только имя нового файла — путь указывать не надо. Иначе получите ошибку.

Удаление файла

Sub Delete_File()
    Dim objFSO As Object, objFile As Object
    Dim sFileName As String
 
    sFileName = "C:WWW.xls"    'имя файла для удаления
    'создаем объект FileSystemObject    
    Set objFSO = CreateObject("Scripting.FileSystemObject")
    'проверяем наличие файла по указанному пути
    If objFSO.FileExists(sFileName) = False Then 
        MsgBox "Нет такого файла", vbCritical, "www.excel-vba.ru"
        Exit Sub
    End If
    'удаляем файл
    Set objFile = objFSO.GetFile(sFileName)
    objFile.Delete
    MsgBox "Файл удален", vbInformation, "www.excel-vba.ru"
End Sub

 

Точно так же можно перемещать, копировать и удалять целые папки:

Копирование папки

Sub Copy_Folder()
    Dim objFSO As Object
    Dim sFolderName As String, sNewFolderName As String
 
    sFolderName = "C:test"        'имя исходной папки
    sNewFolderName = "D:tmp"     'имя папки, в которую копируем(нужен слеш на конце)
    'создаем объект FileSystemObject    
    Set objFSO = CreateObject("Scripting.FileSystemObject")
    'проверяем наличие папки по указанному пути
    If objFSO.FolderExists(sFolderName) = False Then 
        MsgBox "Нет такой папки", vbCritical, "www.excel-vba.ru"
        Exit Sub
    End If
    'копируем папку
    objFSO.CopyFolder sFolderName, sNewFolderName
 
    MsgBox "Папка скопирована", vbInformation, "www.excel-vba.ru"
End Sub
Sub Move_Folder()
    Dim objFSO As Object
    Dim sFolderName As String, sNewFolderName As String
 
    sFolderName = "C:test"           'имя исходной папки
    sNewFolderName = "C:tmptest"   'имя папки, в которую перемещаем(нужен слеш на конце)
    'создаем объект FileSystemObject    
    Set objFSO = CreateObject("Scripting.FileSystemObject")
    'проверяем наличие папки по указанному пути
    If objFSO.FolderExists(sFolderName) = False Then 
        MsgBox "Нет такой папки", vbCritical, "www.excel-vba.ru"
        Exit Sub
    End If
    'перемещаем папку
    objFSO.MoveFolder sFolderName, sNewFolderName
    MsgBox "Папка перемещена", vbInformation, "www.excel-vba.ru"
End Sub
Sub Rename_Folder()
    Dim objFSO As Object, objFolder As Object
    Dim sFolderName As String, sNewFolderName As String
 
    sFolderName = "C:test"            'имя исходной папки
    'имя папки для переименования(только имя, без полного пути)
    sNewFolderName = "new folder name"
    'создаем объект FileSystemObject    
    Set objFSO = CreateObject("Scripting.FileSystemObject")
    'проверяем наличие папки по указанному пути
    If objFSO.FolderExists(sFolderName) = False Then 
        MsgBox "Нет такой папки", vbCritical, "www.excel-vba.ru"
        Exit Sub
    End If
    'переименовываем папку
    'получаем доступ к объекту Folder(папка)
    Set objFolder = objFSO.GetFolder(sFolderName)
    'назначаем новое имя
    objFolder.Name = sNewFolderName
    MsgBox "Папка переименована", vbInformation, "www.excel-vba.ru"
End Sub
Sub Delete_Folder()
    Dim objFSO As Object, objFolder As Object
    Dim sFolderName As String
 
    sFolderName = "C:test"    'имя папки для удаления
    'создаем объект FileSystemObject    
    Set objFSO = CreateObject("Scripting.FileSystemObject")
    'проверяем наличие папки по указанному пути
    If objFSO.FolderExists(sFolderName) = False Then 
        MsgBox "Нет такой папки", vbCritical, "www.excel-vba.ru"
        Exit Sub
    End If
    'удаляем папку
    objFSO.DeleteFolder sFolderName
    MsgBox "Папка удалена", vbInformation, "www.excel-vba.ru"
End Sub

FSO, конечно, способен на большее — но цель данной статьи была показать основные операции с папками и файлами как стандартными методами, так и более продвинутыми.


Статья помогла? Поделись ссылкой с друзьями!

  Плейлист   Видеоуроки


Поиск по меткам



Access
apple watch
Multex
Power Query и Power BI
VBA управление кодами
Бесплатные надстройки
Дата и время
Записки
ИП
Надстройки
Печать
Политика Конфиденциальности
Почта
Программы
Работа с приложениями
Разработка приложений
Росстат
Тренинги и вебинары
Финансовые
Форматирование
Функции Excel
акции MulTEx
ссылки
статистика

VBA in Excel does not restrict us to just a single application. VBA gives us access to the windows environment too. With this we can perform a lot of common file-based actions. One of the most common is to rename a file. In this post, we will look at 5 examples of renaming files with VBA.

To rename a file with VBA we use the Name command. Name appears in blue because it is a reserved word within VBA.

Example 1: Renaming a file

This example renames a file from Example File.xlsx to Example File Renamed.xlsx.

Sub VBARenameFile()

Name "C:UsersmarksDocumentsExample File.xlsx" As _
    "C:UsersmarksDocumentsExample File Renamed.xlsx"

End Sub

Example 2: Rename a file based on cell values

In this example, we rename a file based on cell values. The screenshot below shows the current file name in Cell C2 and the new file name in Cell C4.

Example - VBA Rename File

We can run the following macro to rename a file using these cell values.

Sub VBARenameFileSheetNames()

Name ActiveSheet.Range("C2") As _
    ActiveSheet.Range("C4")

End Sub

Example 3: Move a file with the Name command

Did you notice the Name command requires the file path and file name? Therefore, the Name command doesn’t just rename files but can also move files. For example, the code below moves the file from C:UsersmarksDocuments to C:Usersmarks, but the file name remains the same.

Sub VBAMoveFile()

Name "C:UsersmarksDocumentsExample File.xlsx" As _
    "C:UsersmarksExample File.xlsx"

End Sub

Example 4: Avoiding errors when renaming files

Trying to move files that don’t exist, or are locked for editing can trigger errors. The errors are detailed in the section below.

If there is an error, we really want to avoid going through the Visual Basic error debugging process. Instead, a better option is to display a message box with an OK button.

Sub VBAAdvancedRenameFile()

'Create variables to hold file names
Dim filePath As String
Dim newFilePath As String

filePath = "C:UsersmarksDocumentsExample File.xlsx"
newFilePath = "C:UsersmarksDocumentsExample File Renamed.xlsx"

'Ignore errors
On Error Resume Next

'Rename file
Name filePath As newFilePath

'Display message if error occured
If Err.Number <> 0 Then
    MsgBox Prompt:="Unable to rename file", Buttons:=vbOK, _
        Title:="Rename file error"
End If

'Turn error checking back on
On Error GoTo 0

End Sub

Example 5: Reusable function

Finally, let’s create a reusable function for moving and renaming files.

The VBA function below accepts two string arguments; the existing file path and the new file path.

Function fxRenameFile(filePath As String, newFilePath As String)

'Ignore errors
On Error Resume Next

'Rename file
Name filePath As newFilePath

'Display message if error occured
If Err.Number <> 0 Then
    fxRenameFile = False
Else
    fxRenameFile = True
End If

'Turn error checking back on
On Error GoTo 0

End Function

We can use this function in two ways.

  1. Calling the function from another macro
  2. Calling the function from a worksheet

Let’s look at both of these in turn.

Calling the function from a macro

The macro below calls the function and displays a message box with the following values:

  • True = File renamed
  • False = Error occurred.
Sub CallFunction()

'Create variables to hold file names
Dim filePath As String
Dim newFilePath As String

filePath = "C:UsersmarksDocumentsExample File.xlsx"
newFilePath = "C:UsersmarksDocumentsExample File Renamed.xlsx"

'True = File Renamed
'False = Error Occured
MsgBox fxRenameFile(filePath, newFilePath)

End Sub

Calling the function from a worksheet

Alternatively, we can call the function just like a normal worksheet function.

Calling function to rename file from worksheet

Look at the screenshot above, our custom function is used in Cell C6:

=fxRenameFile(C2,C4)

TRUE indicates that the file named in Cell C2 has been successfully renamed to the file named in Cell C4. If we run the function a second time, it will show FALSE, as the file has already been renamed.

Be aware the function executes each time cells C2 or C4 change, so be careful with the order in which you update the cells.

TOP TIP: If we use the fxRenameFile function inside an IF function, it will only executes when the condition is met. In the example below, the fxRenameFile function only executes if cell A6 equals Y.

=IF(A6="Y",fxRenameFile(C2,C4),"Do not rename")

Using this method, we can control when and how the function executes. We just need to change cell A6 to another value when we don’t the function to execute.

Possible errors

If we try to rename a file or folder path that does not exist, it triggers an error: Run-time error’53’: File not found.

VBA Rename File error

If the new file name is the same as an existing one, it triggers the following error: Run-time error ’58’: File already exists.

Rename file to an existing open file

If either file name is not a valid format, it triggers the following error: Run-time error ‘5’: Invalid procedure call or argument

Invalid file name error when renaming a file with VBA

Notes on renaming files

We have used Excel workbooks in the examples, but we can use any file type. Also, we are not restricted to files; we can rename folders using the Name command too.

The Name command is core Visual Basic code. Therefore, it exists in other applications supporting VBA, such as Word and PowerPoint.

Related Posts:

  • VBA code to copy, move, delete and manage files.
  • VBA code library
  • VBA Copy File – How to + 5 examples

Headshot Round

About the author

Hey, I’m Mark, and I run Excel Off The Grid.

My parents tell me that at the age of 7 I declared I was going to become a qualified accountant. I was either psychic or had no imagination, as that is exactly what happened. However, it wasn’t until I was 35 that my journey really began.

In 2015, I started a new job, for which I was regularly working after 10pm. As a result, I rarely saw my children during the week. So, I started searching for the secrets to automating Excel. I discovered that by building a small number of simple tools, I could combine them together in different ways to automate nearly all my regular tasks. This meant I could work less hours (and I got pay raises!). Today, I teach these techniques to other professionals in our training program so they too can spend less time at work (and more time with their children and doing the things they love).


Do you need help adapting this post to your needs?

I’m guessing the examples in this post don’t exactly match your situation. We all use Excel differently, so it’s impossible to write a post that will meet everybody’s needs. By taking the time to understand the techniques and principles in this post (and elsewhere on this site), you should be able to adapt it to your needs.

But, if you’re still struggling you should:

  1. Read other blogs, or watch YouTube videos on the same topic. You will benefit much more by discovering your own solutions.
  2. Ask the ‘Excel Ninja’ in your office. It’s amazing what things other people know.
  3. Ask a question in a forum like Mr Excel, or the Microsoft Answers Community. Remember, the people on these forums are generally giving their time for free. So take care to craft your question, make sure it’s clear and concise.  List all the things you’ve tried, and provide screenshots, code segments and example workbooks.
  4. Use Excel Rescue, who are my consultancy partner. They help by providing solutions to smaller Excel problems.

What next?
Don’t go yet, there is plenty more to learn on Excel Off The Grid.  Check out the latest posts:

I spent a lot of time doing this recently, because I disliked having to delete previous files when I did «Save As» — I wanted a «Save as and delete old file» answer. My answer is copied from here.

I added it to the quicklaunch bar which works wonderfully.

  1. Insert following code into normal.dotm template (found in C:Documents and Settingsuser nameApplication DataMicrosoftTemplates for Windows 7 for Word)
  2. Save normal.dotm
  3. Add this to the quicklaunch toolbar in Word.
  4. Optional — remap a keyboard shortcut to this
  5. Optional — digitally sign your template (recommended)

Note this actually moves the old file to the Recycle Bin rather than trashing completely and also sets the new file name in a very convenient fashion.


Option Explicit

 'To send a file to the recycle bin, we'll need to use the Win32 API
 'We'll be using the SHFileOperation function which uses a 'struct'
 'as an argument. That struct is defined here:
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 Long
End Type

 ' function declaration:
Private Declare Function SHFileOperation Lib "shell32.dll" Alias "SHFileOperationA" (lpFileOp As SHFILEOPSTRUCT) As Long

 'there are some constants to declare too
Private Const FO_DELETE = &H3
Private Const FOF_ALLOWUNDO = &H40
Private Const FOF_NOCONFIRMATION = &H10
Private Const FOF_SILENT = &H4

Function RecycleFile(FileName As String, Optional UserConfirm As Boolean = True, Optional HideErrors As Boolean = False) As Long
     'This function takes one mandatory argument (the file to be recycled) and two
     'optional arguments: UserConfirm is used to determine if the "Are you sure..." dialog
     'should be displayed before deleting the file and HideErrors is used to determine
     'if any errors should be shown to the user

    Dim ptFileOp As SHFILEOPSTRUCT
     'We have declared FileOp as a SHFILEOPSTRUCT above, now to fill it:
    With ptFileOp
        .wFunc = FO_DELETE
        .pFrom = FileName
        .fFlags = FOF_ALLOWUNDO
        If Not UserConfirm Then .fFlags = .fFlags + FOF_NOCONFIRMATION
        If HideErrors Then .fFlags = .fFlags + FOF_SILENT
    End With
     'Note that the entire struct wasn't populated, so it would be legitimate to change it's
     'declaration above and remove the unused elements. The reason we don't do that is that the
     'struct is used in many operations, some of which may utilise those elements

     'Now invoke the function and return the long from the call as the result of this function
    RecycleFile = SHFileOperation(ptFileOp)

End Function


Sub renameAndDelete()

    ' Store original name
    Dim sOriginalName As String
    sOriginalName = ActiveDocument.FullName

    ' Save As
    Dim sFilename As String, fDialog As FileDialog, ret As Long
    Set fDialog = Application.FileDialog(msoFileDialogSaveAs)

    'set initial name so you don't have to navigate to
    fDialog.InitialFileName = sOriginalName

    ret = fDialog.Show

    If ret <> 0 Then
        sFilename = fDialog.SelectedItems(1)
    Else
        Exit Sub
    End If

    Set fDialog = Nothing

    'only do this if the file names are different...
    If (sFilename <> sOriginalName) Then
        'I love vba's pretty code
         ActiveDocument.SaveAs2 FileName:=sFilename, FileFormat:= _
            wdFormatXMLDocument, LockComments:=False, Password:="", AddToRecentFiles _
            :=True, WritePassword:="", ReadOnlyRecommended:=False, EmbedTrueTypeFonts _
            :=False, SaveNativePictureFormat:=False, SaveFormsData:=False, _
            SaveAsAOCELetter:=False, CompatibilityMode:=14

        ' Delete original (don't care about errors, I guess)
        Dim hatersGonnaHate As Integer
        hatersGonnaHate = RecycleFile(sOriginalName, False, True)

    End If

End Sub

Формулировка задачи:

Здравствуйте. Создаю новый документ:

И затем отображаю word:

Вопрос: можно ли переименовать новый документ вместо «Документ1», «Документ2» и т.д. на свое название. Например на: «Это мой документ»?

Код к задаче: «Переименовать новый word-документ»

textual

Dim dlgResult
  With WApp.Dialogs(wdDialogFileSaveAs)
    .Name = "Это мой документ"
    dlgResult = .Show
  End With
  If dlgResult = -1 Then
    'документ был сохранен
  Else
    'юзер отменил диалог
  End If

Полезно ли:

12   голосов , оценка 4.083 из 5

Понравилась статья? Поделить с друзьями:
  • Как перезапустить microsoft excel
  • Как перезагрузить программу word
  • Как переделать число как текст в excel
  • Как переделать цифры в буквы excel
  • Как переделать фото документ в документ word