Eliminar un archivo en VBA


Usando VBA, ¿cómo puedo:

  1. probar si existe un archivo, y si es así,
  2. eliminarlo?
Author: ZygD, 2008-09-16

9 answers

1.) Marque aquí. Básicamente haz esto:

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

Voy a dejar a usted para averiguar los diversos manejo de errores necesarios, pero estas son algunas de las cosas de manejo de errores que estaría considerando:

  • Compruebe si se pasa una cadena vacía.
  • Compruebe si hay una cadena que contenga caracteres ilegales en un nombre de archivo/ruta

2. Cómo Eliminar un Archivo. Mira esto. Básicamente usa el comando Kill pero necesitas permitir la posibilidad de un archivo ser de solo lectura. Aquí hay una función para usted:

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

De nuevo, te dejaré el manejo de errores a ti y de nuevo estas son las cosas que consideraría:

  • ¿Debería esto comportarse de manera diferente para un directorio frente a un archivo? ¿Debería un usuario tener que indicar explícitamente que desea eliminar un directorio?

  • ¿Desea que el código restablezca automáticamente el atributo de solo lectura o debe darse al usuario algún tipo de indicación de que el atributo de solo lectura está establecido?


EDITAR: Marcar esta respuesta como wiki de la comunidad para que cualquiera pueda modificarla si es necesario.

 135
Author: Onorio Catenacci,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-09-06 06:49:42

Una forma alternativa de codificar la respuesta de Brettski, con la que estoy totalmente de acuerdo, podría ser

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

Mismo efecto pero menos declaraciones de variables (bueno, ninguna).

FileSystemObject es una herramienta muy útil y con la que vale la pena ser amigable. Aparte de cualquier otra cosa, para la escritura de archivos de texto, a veces puede ser más rápido que la alternativa heredada, lo que puede sorprender a algunas personas. (En mi experiencia al menos, YMMV).

 43
Author: Mike Woodhouse,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-03-04 13:17:39

Probablemente me quemaré por esto, pero ¿cuál es el punto de probar la existencia si solo lo vas a eliminar? Uno de mis principales problemas es una aplicación que lanza un cuadro de diálogo de error con algo como " No se pudo eliminar el archivo, no existe!"

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.

Si el archivo no existe, en primer lugar, ¡misión cumplida!

 10
Author: JohnFx,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-08-02 18:31:16

Se puede usar lo siguiente para probar la existencia de un archivo y luego eliminarlo.

Dim aFile As String
aFile = "c:\file_to_delete.txt"
If Len(Dir$(aFile)) > 0 Then
     Kill aFile
End If 
 9
Author: Rich Adams,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2008-09-15 23:12:09

En VB es normalmente Dir para encontrar el directorio del archivo. Si no está en blanco, entonces existe y luego use Kill para deshacerse del archivo.

test = Dir(Filename)
If Not test = "" Then
    Kill (Filename)
End If
 6
Author: Leo Moore,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-12-28 08:28:30

Establezca una referencia al Scripting.Runtime library y luego use el FileSystemObject:

Dim fso as New FileSystemObject, aFile as File

if (fso.FileExists("PathToFile")) then
    aFile = fso.GetFile("PathToFile")
    aFile.Delete
End if
 4
Author: Brettski,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2008-09-15 23:40:20

Aquí hay un consejo: ¿está reutilizando el nombre del archivo o planea hacer algo que requiera la eliminación inmediata?

No?

Puede obtener VBA para disparar el comando DEL "C:\TEMP\scratchpad.txt " / F desde el símbolo del sistema asincrónicamente usando VBA.Shell:

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

Tenga en cuenta las comillas dobles (carácter ASCII 34) alrededor del nombre del archivo: Asumo que tiene una ruta de red o un nombre de archivo largo conteniendo espacios.

Si es un archivo grande, o está en una conexión de red lenta, fire-and-forget es el camino a seguir. Por supuesto, nunca se llega a ver si esto funcionó o no; pero se reanuda su VBA inmediatamente, y hay momentos en que esto es mejor que esperar a la red.

 3
Author: Nile,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-10-08 15:11:22

Puede establecer una referencia al Scripting.Biblioteca de tiempo de ejecución y, a continuación, utilice FileSystemObject. Tiene un método DeleteFile y un método FileExists.

Vea el artículo de MSDN aquí.

 2
Author: Darrel Miller,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2008-09-15 23:12:37

2 líneas de código en VBA..

Set FSO = CreateObject("Scripting.FileSystemObject")
If FSO.FileExists(strPath) Then FSO.DeleteFile ("" & strPath & "")
 0
Author: Zach Minot,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-04-03 22:25:14