Vba excel удалить файл без подтверждения

Удаление любых файлов из кода VBA Excel с помощью оператора Kill и метода DeleteFile объекта FileSystemObject. Знаки подстановки, синтаксис, примеры.

Оператор Kill

Описание

Kill – это оператор, предназначенный для удаления файлов с диска.

Синтаксис

  • PathName – это строковое выражение, задающее одно или несколько имен файлов (по шаблону), которые требуется удалить.

Строка PathName может содержать каталоги (папки) и букву диска. Если файл с именем PathName не существует, будет сгенерирована ошибка.

Оператор Kill поддерживает использование знаков подстановки в последнем компоненте параметра PathName (собственное имя файла без пути к нему):

  • Звездочка (*) – заменяет любое количество символов или ни одного.
  • Вопросительный знак (?) – заменяет один символ или ни одного.

Знаки подстановки позволяют создать шаблон, по которому можно удалить сразу несколько файлов.

Примеры

Пример 1
Удаление одного файла без проверки его существования (в примере — удаление книги Excel):

Sub Primer1()

  On Error Resume Next

  Kill ThisWorkbook.Path & «Книга1.xlsx»

End Sub

Инструкция On Error Resume Next нужна для того, чтобы корректно завершить программу в том случае, если файла с именем PathName не существует.

Пример 2
Удаление одного файла с проверкой его существования:

Sub Primer2()

Dim myPathName As String

  myPathName = «C:Новая папкаФайл1.docx»

  If Dir(myPathName) <> «» Then Kill myPathName

End Sub

Пример 3
Удаление нескольких файлов по шаблону:

Sub Primer3()

  On Error Resume Next

  Kill «C:Новая папкаСправка*»

End Sub

В результате работы этого кода VBA Excel будут удалены все файлы с любыми расширениями, которые начинаются со слова «Справка». Если строку Kill "C:Новая папкаСправка*" заменить строкой Kill "C:Новая папка*2020*", она удалит все файлы, в имени которых есть подстрока «2020».

Как удалить объект ThisWorkbook с помощью оператора Kill из кода VBA Excel, размещенного в нем же, смотрите в статье: Удаление книги из собственного кода.

Метод DeleteFile

Описание

DeleteFile – это метод объекта FileSystemObject, предназначенный для удаления файлов с диска из кода VBA Excel.

Синтаксис

Object.DeleteFile PathName, [force]

  • Object – переменная, возвращающая объект FileSystemObject (обязательный параметр);
  • PathName – строковое выражение, задающее одно или несколько имен файлов (по шаблону), которые требуется удалить (обязательный параметр);
  • force – значение типа Boolean: True – удаляются все файлы, False (по умолчанию) – не удаляются файлы с атрибутом «только для чтения» (необязательный параметр).

В последнем компоненте параметра PathName (собственное имя файла без пути к нему) можно использовать знаки подстановки, также, как и для оператора Kill. Если указанный файл не существует, будет сгенерирована ошибка.

Примеры

Пример 4
Удаление одного файла с проверкой его существования:

Sub Primer4()

Dim fso As Object

‘Присваиваем переменной fso ссылку на новый экземпляр FileSystemObject

Set fso = CreateObject(«Scripting.FileSystemObject»)

‘Проверяем существование удаляемого файла

  If Dir(ThisWorkbook.Path & «Изображение.png») <> «» Then

    ‘Удаляем файл, если он существует

    fso.DeleteFile ThisWorkbook.Path & «Изображение.png»

  End If

End Sub

Пример 5
Удаление нескольких или всех файлов по шаблону:

Sub Primer5()

Dim fso As Object

‘Присваиваем переменной fso ссылку на новый экземпляр FileSystemObject

Set fso = CreateObject(«Scripting.FileSystemObject»)

‘Завершаем программу, если не существует ни одного файла, подходящего под указанный шаблон

On Error Resume Next

‘Удаляем указанный файл (файлы)

fso.DeleteFile «C:Новая папка*.docx»

End Sub

В результате работы этого кода VBA Excel из папки «Новая папка» будут удалены все файлы с расширением .docx.


Фразы для контекстного поиска: удаление файла, удаление всех файлов, удаление нескольких книг, удаление всех книг, удаление по шаблону.


Using VBA, how can I:

  1. test whether a file exists, and if so,
  2. delete it?

1.) Check here. Basically do this:

Function FileExists(ByVal FileToTest As String) As Boolean
   FileExists = (Dir(FileToTest) <> "")
End Function

I’ll leave it to you to figure out the various error handling needed but these are among the error handling things I’d be considering:

  • Check for an empty string being passed.
  • Check for a string containing characters illegal in a file name/path

2.) How To Delete a File. Look at this. Basically use the Kill command but you need to allow for the possibility of a file being read-only. Here’s a function for you:

Sub DeleteFile(ByVal FileToDelete As String)
   If FileExists(FileToDelete) Then 'See above          
      ' First remove readonly attribute, if set
      SetAttr FileToDelete, vbNormal          
      ' Then delete the file
      Kill FileToDelete
   End If
End Sub

Again, I’ll leave the error handling to you and again these are the things I’d consider:

  • Should this behave differently for a directory vs. a file? Should a user have to explicitly have to indicate they want to delete a directory?

  • Do you want the code to automatically reset the read-only attribute or should the user be given some sort of indication that the read-only attribute is set?


EDIT: Marking this answer as community wiki so anyone can modify it if need be.

2

An alternative way to code Brettski’s answer, with which I otherwise agree entirely, might be

With New FileSystemObject
    If .FileExists(yourFilePath) Then
        .DeleteFile yourFilepath
    End If
End With

Same effect but fewer (well, none at all) variable declarations.

The FileSystemObject is a really useful tool and well worth getting friendly with. Apart from anything else, for text file writing it can actually sometimes be faster than the legacy alternative, which may surprise a few people. (In my experience at least, YMMV).

answered Sep 16, 2008 at 11:03

Mike Woodhouse's user avatar

Mike WoodhouseMike Woodhouse

51.5k12 gold badges88 silver badges127 bronze badges

4

I’ll probably get flamed for this, but what is the point of testing for existence if you are just going to delete it? One of my major pet peeves is an app throwing an error dialog with something like «Could not delete file, it does not exist!»

On Error Resume Next
aFile = "c:file_to_delete.txt"
Kill aFile
On Error Goto 0
return Len(Dir$(aFile)) > 0 ' Make sure it actually got deleted.

If the file doesn’t exist in the first place, mission accomplished!

answered Sep 15, 2008 at 23:34

JohnFx's user avatar

4

The following can be used to test for the existence of a file, and then to delete it.

Dim aFile As String
aFile = "c:file_to_delete.txt"
If Len(Dir$(aFile)) > 0 Then
     Kill aFile
End If 

answered Sep 15, 2008 at 23:12

Rich Adams's user avatar

Rich AdamsRich Adams

25.9k4 gold badges39 silver badges62 bronze badges

2

In VB its normally Dir to find the directory of the file. If it’s not blank then it exists and then use Kill to get rid of the file.

test = Dir(Filename)
If Not test = "" Then
    Kill (Filename)
End If

ZygD's user avatar

ZygD

21k39 gold badges77 silver badges98 bronze badges

answered Sep 15, 2008 at 23:11

Leo Moore's user avatar

Leo MooreLeo Moore

2,0982 gold badges19 silver badges21 bronze badges

set a reference to the Scripting.Runtime library and then use the FileSystemObject:

Dim fso as New FileSystemObject, aFile as File

if (fso.FileExists("PathToFile")) then
    aFile = fso.GetFile("PathToFile")
    aFile.Delete
End if

answered Sep 15, 2008 at 23:40

Brettski's user avatar

BrettskiBrettski

19.1k15 gold badges75 silver badges95 bronze badges

2

Here’s a tip: are you re-using the file name, or planning to do something that requires the deletion immediately?

No?

You can get VBA to fire the command DEL «C:TEMPscratchpad.txt» /F from the command prompt asynchronously using VBA.Shell:

Shell «DEL » & chr(34) & strPath & chr(34) & » /F «, vbHide

Note the double-quotes (ASCII character 34) around the filename: I’m assuming that you’ve got a network path, or a long file name containing spaces.

If it’s a big file, or it’s on a slow network connection, fire-and-forget is the way to go.
Of course, you never get to see if this worked or not; but you resume your VBA immediately, and there are times when this is better than waiting for the network.

1

You can set a reference to the Scripting.Runtime library and then use the FileSystemObject. It has a DeleteFile method and a FileExists method.

See the MSDN article here.

answered Sep 15, 2008 at 23:12

Darrel Miller's user avatar

Darrel MillerDarrel Miller

138k31 gold badges193 silver badges242 bronze badges

0

A shorter version of the first solution that worked for me:

Sub DeleteFile(ByVal FileToDelete As String)
   If (Dir(FileToDelete) <> "") Then
      ' First remove readonly attribute, if set
      SetAttr FileToDelete, vbNormal
      ' Then delete the file
      Kill FileToDelete
   End If
End Sub

Return to VBA Code Examples

VBA allows you to delete an existing file, using the Kill command. In this tutorial, you will learn how to delete a specific file or multiple files.

If you want to learn how to copy and rename a file, you can click on this link: VBA Copy File

Delete a Single File (or Workbook) in VBA

We will show how to delete the file Sample file 1.xlsx in the folder VBA Folder. The folder with the file now looks like in Image 1:

vba-delete-file

Image 1. Delete a single file

Here is the code which will delete the file:

Kill "C:VBA FolderSample File 1.xlsx"

After running the code, the file Sample file 1.xlsx is now deleted from the VBA Folder. The output is in Image 2:

vba-delete-file-result

Image 2. File deleted from the C:VBA Folder

Delete All Excel Files From the Folder

The same command enables you to delete all Excel files from the folder. You just need to put an asterisk (*) instead of the file name. An asterisk replaces any string. Here is the code:

Kill "C:VBA Folder*.xlsx"

As you can see in Image 3, all Excel files from Folder VBA are deleted:

vba-delete-all-files

Image 3. Delete all Excel files from the C:VBA Folder

VBA Coding Made Easy

Stop searching for VBA code online. Learn more about AutoMacro — A VBA Code Builder that allows beginners to code procedures from scratch with minimal coding knowledge and with many time-saving features for all users!
vba save as

Learn More!

Home / VBA / VBA Delete Workbook (Excel File)

To delete an Excel file from a folder you can use two different methods. The first method is the “Kill” statement which takes the file path to refer to the file that you wish to delete. The second method is the FileSystemObject object which has a method associated with it to delete a file.

To use these codes, go to the VBE (Code Editor) from the developer tab.

Delete a File using VBA (Kill Function)

Kill function helps you to delete a single file or multiple files, and use wildcard characters to delete more than one file. Below is the one-line code that deletes the file from the folder that I have on the desktop.

Kill "C:UsersDellDesktopSample Datafile-one.xlsx"

This code will show you an error if the workbook that you specified to delete doesn’t exist.

Helpful Links: Run a Macro – Macro Recorder – Visual Basic Editor – Personal Macro Workbook

Delete All the Files from a Folder using VBA

And if you want to delete all the files that you have in a folder, you can use a wildcard character.

Kill "C:UsersDellDesktopSample Data*.xl*"

Delete a File using the FileSystemObject (Object)

The file system object provides you with access to the computer’s file system. You can learn about it from here, but now, let’s write a code to remove a file.

Full Code

Sub vba_delete_file()
Dim FSO
Dim myFile As String
Set FSO = CreateObject("Scripting.FileSystemObject")
myFile = "C:UsersDellDesktopSample Datafile1.xlsx"
FSO.DeleteFile myFile, True
End Sub

Let’s say you need to write a code that can check for a file, (exists or not) and then delete it. Here’s the code that you need.

Sub vba_delete_file()
Dim FSO
Dim myFile As String
Set FSO = CreateObject("Scripting.FileSystemObject")
myFile = "C:UsersDellDesktopSample Datafile1.xlsx"
If FSO.FileExists(myFile) Then
    FSO.DeleteFile myFile, True
    MsgBox "Deleted"   
Else
    MsgBox "There's no workbook with this name."   
End If   
End Sub

More on VBA Workbooks

VBA Save Workbook | VBA Close Workbook | VBA ThisWorkbook | VBA Rename Workbook | VBA Activate Workbook | VBA Combine Workbook | VBA Protect Workbook (Unprotect) | VBA Check IF a Workbook is Open | VBA Open Workbook | VBA Check IF an Excel Workbook Exists in a Folder| VBA Create New Workbook (Excel File)

  • VBA Workbook

Description

The VBA Kill function deletes a file based on the provided pathname.

If using Windows you can also use the FileSystemObject VBA DeleteFile method which allows you to delete a file or folder.

Syntax

The syntax for the Kill function is:

Kill( pathname )

Parameters

Parameter Variable Type Description
pathname String The pathname of the file you want to delete or a pathname including wildcards.

Other Notes

The Kill function’s pathname parameter can include wildcards. You can use wildcard characters to specify multiple files to be deleted. The patterns that you can choose from are:

Wildcard Description
* Allows you to match any string of any length (including zero length)
? Allows you to match on a single character

The VBA Kill function will not delete readonly files.

Example usage

The Kill function can be used in VBA. Let’s look at some Kill function examples:

Kill "somefile.txt"
Result: Deletes file "somefile.txt" in the current directory

Kill "C:*.txt"
Result: Deletes all txt files under drive C:

As mentioned above the VBA Kill function will not delete readonly files. Therefore to delete a file in VBA you need to make sure its file property is set to vbNormal (use SetAttr function). Similarly it is good to verify if the file exists before attempting to delete it. The function below takes care of both:

Public Function KillFile(filePath As String) as Boolean
    If Len(Dir(filePath)) > 0 Then
        SetAttr filePath, vbNormal
        Kill filePath
        KillFile = true
        Exit Function
    End If
    KillFile = false
End Function

Sub ExampleKill()
   If KillFile("C:test.txt") Then Debug.Print "Killed successfully!"
End Sub

Recursive file deleting

In some cases you might want to delete all files of a certain filename in the directory and all subsequent directories. In this case in my post Deleting files using VBA I explored a recursive file delete function:

Sub RecursiveKill(filePath As String, fileName As String)
    Dim currDir As String
    Dim currentPath As String, dirItem As Variant
    Dim dirCollection As Collection
    Set dirCollection = New Collection
    
    'Delete the file in current Directory
    If Len(Dir(filePath & fileName)) > 0 Then
       SetAttr filePath & fileName, vbNormal
       Kill filePath & fileName
    End If
    'Delete the file recursively in remaining directories
    currDir = Dir(filePath, vbDirectory)
    Do Until currDir = vbNullString
        If Left(currDir, 1) <> "." And (GetAttr(filePath & currDir) And vbDirectory) = vbDirectory Then
            dirCollection.Add filePath & currDir & ""
        End If
        currDir = Dir()
    Loop
     
    For Each dirItem In dirCollection
        RecursiveKill CStr(dirItem), fileName
    Next dirItem
End Sub

Delete all copies of file “1.txt” in the given and below directories like this:

RecursiveKill "C:some_path", "1.txt" 

Удаление файлов с помощью VBA в Excel

Добрый день, уважаемые читатели блога! Как водится, сегодня мы поговорим о программе Excel, но в не совсем привычной для нас функции — файловом менеджере. Постараюсь ответить на вопрос — может ли Excel с помощью макросов удалять файлы?

Ответ однозначный — да. Для этого в языке VBA есть специальный оператор — kill. Для нас он и представляет определённый интерес. 

Давайте посмотрим как его можно использовать. Имеется папка (в моём примере это C:Для всех), её нужно очистить от файлов с расширением *.xlsx.

Удаление файлов с помощью VBA в Excel

Создадим новую книгу и, как обычно, добавим в неё стандартный модуль. Мы рассматривали этот алгоритм в предыдущих статьях.

  • вкладка «Разработчик», кнопка «Visual basic»;
  • вставляем новый модуль и помещаем следующий код макроса.

Sub DF()
‘ Удаление всех файлов из папки с расширением .xlsx
Kill «C:Для всех» & «*.xlsx»
End Sub

Удаление файлов с помощью VBA в Excel

Будьте внимательны — макрос не удаляет файлы в «Корзину», а полностью стирает их с жёсткого диска компьютера! 

Аналогично сочетанию клавиш Shift+Delete.

Проверим работоспособность нашего кода. Запустим окно выбора макросов комбинацией клавиш Alt+F8 и нажмём «Выполнить».

Удаление файлов с помощью VBA в Excel

Результат на лицо — в папке остался только один файл «Изменение листа.xlsm» потому что у него разрешение не совпадает с указанным в макросе.

Также хочется отметить, что привычное сочетание клавиш Ctrl+Z не поможет восстановить файлы.

Удаление файлов с помощью VBA в Excel

Необходимая оговорка — макрос можно использовать для всех типов файлов. Для этого необходимо изменить в макросе расширение *.xlsx на нужное для удаления вам.

0 / 0 / 0

Регистрация: 06.12.2006

Сообщений: 10

1

Удаление листа без запроса на подтверждение.

07.12.2006, 19:12. Показов 77867. Ответов 2


Студворк — интернет-сервис помощи студентам

как решить проблему незаметного удаления листа, чтобы не появлялся запрос на подтверждение?



0



Dim@X

7 / 7 / 0

Регистрация: 16.08.2011

Сообщений: 52

07.12.2006, 19:26

2

Visual Basic
1
2
3
Application.DisplayAlerts = False
Sheets("Лист1").Delete
Application.DisplayAlerts = True



7



0 / 0 / 0

Регистрация: 06.12.2006

Сообщений: 10

07.12.2006, 20:21

 [ТС]

3

Спасибо!



0



In VBA, we can delete any file present in the computer using VBA codes. The code used to delete files is known as the “Kill” command. The method to delete any file is that first, we must provide the file’s path, which means the file’s location on the computer. Then, we use the “Kill” command to delete the file.

Table of contents
  • How to Delete Files using VBA Code?
    • Kill Method to Delete Files in a Folder using VBA Code
    • Delete Particular File Name
    • Delete All Excel Files
    • Delete Entire Folder Only
    • Delete All the Text Files in the Folder
    • Delete Read-Only Files
    • Recommended Articles

How to Delete Files using VBA Code?

VBA is a tough thing initially, but as you spend more time with VBA, you will start loving it just like me. We can open files from another computer folder and work with them. Now, we can delete files as well by using VBA coding. This article will show you how to delete files using VBA code in a specific folder.

When working with large projects, we usually create many intermediate files to support our process. we need to delete those files to avoid future confusion after completing the work.

And one scenario is when we usually receive an email. For example, we save attachments for our regular work, or we want to see the report for that point in time, and later we may need to delete those files.

Deleting those files manually may take time, or we may forget to save them. In addition, it will occupy the space on our computer. Therefore, we will show you how to delete those files with simple VBA codesVBA code refers to a set of instructions written by the user in the Visual Basic Applications programming language on a Visual Basic Editor (VBE) to perform a specific task.read more.

VBA Delete File

You are free to use this image on your website, templates, etc, Please provide us with an attribution linkArticle Link to be Hyperlinked
For eg:
Source: VBA Delete File (wallstreetmojo.com)

Kill Method to Delete Files in a Folder using VBA Code

A simple Kill function will delete the folder, specific file, all Excel files, etc. Take a look at the syntax of the Kill method in VBA. The Kill method cannot delete read-only files.

vba delete file - kill method

Path Name: Pathname is nothing but the folder path in the computer to delete the files.

Note: Path Name can include wildcard characters as well. We can use an asterisk (*) and question marks (?) as wildcard characters in excelIn Excel, wildcards are the three special characters asterisk, question mark, and tilde. Asterisk denotes multiple characters, a question mark denotes a single character, and a tilde denotes the identification of a wild card character.read more.

Asterisk (*) is useful to match any length string. In addition, it also considers zero.

Question mark (?) is useful to match only a single character.

Delete Particular File Name

For example, we have a folder like the one below.

vba delete file example 1.1

We want to delete the file named “File 5” in this folder. But, first, start the code with the Kill function.

Code:

Sub Delete_Files()

Kill(PathName)

End Sub

vba delete file example 1.2

Copy and paste the folder path.

vba delete file example 1.3

And Paste in double-quotes.

Kill "E:Excel Files"

vba delete file example 1.4

Now put one more backward slash () and enter the file name with extension.

Kill "E:Excel FilesFile5.xlsx"

VBA Deletef example 1.5

When you run this code, it will delete the file named “File 5.xlsx” in the mentioned folder path.

Delete All Excel Files

Using VBA, we need to use wildcard characters with the Kill function to delete all the Excel files in the folder. After mentioning the folder path, we need to mention the file as “*.xl*.”

Code:

Kill "E:Excel Files*.xl*"

VBA Deletef example 2.1

When you run this code, it will delete all the Excel files in the folder.

We have seen how we can delete a single Excel file and all the Excel files. But if we want to delete all the files in the folder, how can we delete them? Also, since we are using Excel VBA, can it delete other files?

The answer is Yes! Use the below code to delete all the files in the folder.

Code:

Kill "E:Excel Files*.*"

VBA Deletef example 3.1

Delete Entire Folder Only

Is it possible to delete the entire folder itself?

Yes, it is possible.

We need to delete all the files in the folder using the Kill function. Then to delete the folder, we need to use one more function called RmDir.

Code:

RmDir "E:Excel Files"

VBA Deletef example 4.1

Here RmDir will delete only the empty folder if any subfolder is where it cannot delete them.

Delete All the Text Files in the Folder

To delete all the text files in the folder, use the below code.

Code:

Kill "E:Excel Files*.txt"

VBA Deletef example 5.1

Delete Read-Only Files

As we said, the Kill function cannot delete “Read Only” files in the folder. In such a scenario, we need to use the other two functions: “Dir$” and “SetAttr.” Below is the example code to delete the read-only files as well.

Code:

Sub Delete_Files1()

Dim DeleteFile As String

DeleteFile = " E:Excel Files"

If Len(Dir$(DeleteFile)) > 0 Then

SetAttr DeleteFile, vbNormal

Kill DeleteFile
End If
End Sub

VBA Deletef example 6.1

You can download this VBA Delete File Excel Template from here – VBA Delete File Excel Template.

Recommended Articles

This article has been a guide to VBA Delete Files. Here, we discuss the VBA code to delete 1. Particular File Name, 2. All files, 3. Entire folder, and 4. Read-only Files with downloadable Excel template. Below are some useful articles related to VBA: –

  • VBA InStr
  • VBA Join
  • New Line in Excel VBA
  • Split Function in Excel VBA

9 ответов

1.) Проверьте здесь. В основном это:

Function FileExists(ByVal FileToTest As String) As Boolean
   FileExists = (Dir(FileToTest) <> "")
End Function

Я оставлю это вам, чтобы выяснить, нужна ли обработка ошибок, но они относятся к обработке ошибок, которые я бы рассматривал:

  • Проверьте, не прошла ли пустая строка.
  • Проверьте, что строка, содержащая символы, незаконна в имени файла/пути

2.) Как удалить файл. Посмотрите на this. В основном используйте команду Kill, но вам нужно разрешить доступ к файлу только для чтения. Здесь функция для вас:

Sub DeleteFile(ByVal FileToDelete As String)
   If FileExists(FileToDelete) Then 'See above          
      ' First remove readonly attribute, if set
      SetAttr FileToDelete, vbNormal          
      ' Then delete the file
      Kill FileToDelete
   End If
End Sub

Опять же, я оставлю вам обработку ошибок, и снова это то, что я подумал бы:

  • Должно ли это вести себя по-другому для каталога или файла? Должен ли пользователь явно указывать, что он хочет удалить каталог?

  • Вы хотите, чтобы код автоматически reset атрибут только для чтения или пользователь должен был указать какой-то признак того, что атрибут только для чтения установлен?


EDIT: Отметьте этот ответ как вики сообщества, чтобы любой мог его изменить, если это необходимо.

Onorio Catenacci
15 сен. 2008, в 23:28

Поделиться

Альтернативный способ кодирования ответа Бреттского, с которым я в целом согласен, может быть

With New FileSystemObject
    If .FileExists(yourFilePath) Then
        .DeleteFile yourFilepath
    End If
End With

Тот же эффект, но меньше (ну, вообще-то) никаких объявлений переменных.

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

Mike Woodhouse
16 сен. 2008, в 12:37

Поделиться

Я, вероятно, поплачу за это, но в чем смысл тестирования на существование, если вы просто собираетесь его удалить? Одним из моих главных мошенников для домашних животных является приложение, отображающее диалоговое окно с ошибкой с чем-то вроде «Не удалось удалить файл, его не существует!»

On Error Resume Next
aFile = "c:file_to_delete.txt"
Kill aFile
On Error Goto 0
return Len(Dir$(aFile)) > 0 ' Make sure it actually got deleted.

Если файл не существует в первую очередь, миссия выполнена!

JohnFx
16 сен. 2008, в 00:53

Поделиться

Для проверки наличия файла можно использовать следующее: а затем удалить его.

Dim aFile As String
aFile = "c:file_to_delete.txt"
If Len(Dir$(aFile)) > 0 Then
     Kill aFile
End If 

Rich Adams
15 сен. 2008, в 23:15

Поделиться

В VB его обычно Dir найти каталог файла. Если он не пуст, он существует, а затем используйте Kill, чтобы избавиться от файла.

test = Dir(Filename)
If Not test = "" Then
    Kill (Filename)
End If

Leo Moore
16 сен. 2008, в 00:47

Поделиться

установите ссылку на библиотеку Scripting.Runtime, а затем используйте FileSystemObject:

Dim fso as New FileSystemObject, aFile as File

if (fso.FileExists("PathToFile")) then
    aFile = fso.GetFile("PathToFile")
    aFile.Delete
End if

Brettski
16 сен. 2008, в 00:35

Поделиться

Вот совет: вы повторно используете имя файла или планируете сделать что-то, требующее немедленного удаления?

Нет?

Вы можете заставить VBA запускать команду DEL «C:TEMPscratchpad.txt» /F из командной строки асинхронно с помощью VBA.Shell:

  Shell «DEL» и chr (34) и strPath и chr (34) и «/F», vbHide

Обратите внимание на двойные кавычки (символ ASCII 34) вокруг имени файла: я предполагаю, что у вас есть сетевой путь или длинное имя файла, содержащее пробелы.

Если это большой файл, или он при медленном сетевом подключении, это способ пойти и забыть.
 Конечно, вы никогда не узнаете, работает ли это или нет; но вы немедленно возобновляете свой VBA, и есть моменты, когда это лучше, чем ждать сети.

Nigel Heffernan
02 окт. 2014, в 17:31

Поделиться

Вы можете установить ссылку на библиотеку Scripting.Runtime, а затем использовать FileSystemObject. Он имеет метод DeleteFile и метод FileExists.

См. статью MSDN здесь.

Darrel Miller
16 сен. 2008, в 00:17

Поделиться

2 строки кода в VBA..

Set FSO = CreateObject("Scripting.FileSystemObject")
If FSO.FileExists(strPath) Then FSO.DeleteFile ("" & strPath & "")

Zach Minot
20 март 2018, в 00:08

Поделиться

Ещё вопросы

  • 0Обработка массивов
  • 0Регулярное выражение для поиска символа строки
  • 0Сортировка (числового) массива на основе (числовых) значений другого (не тривиального способа)?
  • 0Запросить выбранные столбцы из двух таблиц с условием условия
  • 0«Docker-compose up» в Windows завершился неудачно с ошибкой на шаге контейнера Mysql
  • 1Facebook SDK: почему Profile.getCurrentProfile () всегда возвращает ноль в первый раз?
  • 0Моя нг-модель не обновляется с первого раза
  • 0как получить значение метки в jquerymobile и разобрать его в int
  • 1альтернатива для Javadoc? [Дубликат]
  • 0при наведении курсора на динамически созданную строку параметры выбора элемента (тега) в строке не раскрываются должным образом. Проблема с Firefox?
  • 0Использование gulp-angular-templatecache для объединения HTML в template.js, получение ошибки $ injector Module Unavailable
  • 0Выберите из таблицы A и B, где записи из таблицы A и таблицы B не существуют в таблице C?
  • 1Python Single Dispatch работает как рекламируется
  • 1Продолжайте округлять до указанной цифры, если не ноль
  • 1Это работает медленно, потому что это в LINQ, или потому что я делаю это плохим способом?
  • 0Как заставить git НЕ заменять содержимое папки?
  • 0получить результат из PHP SQL, но мое «сообщение о результате» не отображается
  • 1Как преобразовать словарь <string, dynamic> в словарь <string, uint>?
  • 0C ++ вставка больше « t» в цикле
  • 0Как установить значение ngOptions по умолчанию, когда опции — это объекты, а по умолчанию — целочисленный идентификатор
  • 0Лучший способ сохранить список объектов с геоданными в Redis
  • 0Сделайте все тело HTML-страницы кликабельным
  • 1Перекрывающиеся раздвижные окна в питоне
  • 0JQuery Fade In / Out вызывает мерцание других DIV
  • 1Выбор строк на основе ближайшей даты в одном столбце к контрольной дате в другом столбце в пандах?
  • 1Python — конвертировать байты / данные Юникода с разделителями табуляции в CSV-файл
  • 1Заполнение сложных объектов из листа Excel и передача его в качестве параметра в [Теорию]
  • 0Проблемы при попытке загрузить файл, нажав на изображение
  • 1Файл XML ImageButton Selector не найден в Eclipse 3.6.1?
  • 1OSGi как жизненный цикл модуля для Angular (2/4)
  • 1ListFragment onCreate вызывается дважды
  • 0Почему кнопки (а также изображения) имеют тенденцию нырять под текстовой строкой?
  • 0Как настроить BrowserSync и / или Angular $ http для совместной работы без проблем cors
  • 0Два поля ввода в одной строке, выровняйте одно слева, а другое справа
  • 1Как вернуть объект при инициализации переменной в Java?
  • 0PHP ассоциативный массив, как читать данные
  • 1В чем разница между созданием Maven и созданием проекта в многокомпонентной сборке?
  • 0Добавить элементы в конец углового списка повторов
  • 1умножение матриц с ndarray
  • 0генерировать первичный ключ, используя дату и время
  • 0rails: форма при отправке должна перейти на пользовательский URL, содержащий значения двух выпадающих меню
  • 1Дата MMS всегда неверна
  • 1Преобразовать вложенные наблюдаемые в одну наблюдаемую
  • 1Создать общее соединение с базой данных для набора систем, подключенных к одной сети
  • 0загружать разный контент в одну и ту же библиотеку?
  • 1OpenMDAO Эффективность внутреннего рекордера низкая?
  • 1Java MulticastSocket отправляет, но не получает
  • 0MYSQL — определить первичный ключ таблицы по порядку
  • 1как перебрать каждую строку в тензоре в тензорном потоке
  • 0Переместить другие элементы, когда элемент находится над

Понравилась статья? Поделить с друзьями:
  • Vba excel удалить текст до символа
  • Vba excel удалить строку содержащую
  • Vba excel удалить строку по условию
  • Vba excel удалить строку в listbox
  • Vba excel удалить содержимое ячеек