Permiso de copia de archivo denegado

Hola,

He creado un código VBA que me permite copiar archivos jpg en un disco duro externo.
Solo copia los archivos según la fecha de creación que he elegido.
También tengo un código VBA que me detecta la letra, por ejemplo F:\, del disco duro externo porque a veces esta letra cambia.

Sin embargo, cada vez que ejecuto mi código VBA, a menudo aparece un error (70) de permiso denegado que me impide copiar los archivos.
Tal vez sea porque la carpeta de destino del disco duro externo está en solo lectura.
Ya desactivé manualmente la solo lectura de esta carpeta, pero se reactiva por sí sola:

Te doy mi código VBA completo porque no se sabe si este error (70) se debe a un fragmento de código que falta o está mal escrito.

Gracias de antemano por tu ayuda

Sheets("cp87").Select
Sheets("macros").Range("a203").Value = ""
Dim appShell As Object
Dim FileName As Variant
Dim FilePath As Variant
Dim oFolder As Object
Dim oFolderItem As Object
Dim testdate As Variant

FolderPath = "D:\Users\Public\IMPORT\TAGSIMPORTAFAIRE\"
FileName = "*.jpg"

EnterDate:
testdate = InputBox("introduce la fecha del renombrado de las etiquetas." & vbCrLf & "Ejemplo: 27/11/2014", "introduce la fecha", (Date))
If testdate = "" Then Exit Sub
If Not IsDate(testdate) Then
MsgBox "La fecha introducida no es válida." & vbCrLf _
& "Por favor, vuelve a introducir la fecha."
GoTo EnterDate
End If
testdate = CDate(testdate)

Set appShell = CreateObject("Shell.Application")
Set oFolder = appShell.Namespace(FolderPath)

For Each oFolderItem In oFolder.Items
If oFolderItem.Name Like FileName Then

If DateValue(oFolder.GetDetailsOf(oFolderItem, 3)) = testdate Then

If Not oFolderItem.Name Like "*TAGSAFAIRE*" Then
a = a + 1
Dim destination As String
Dim objDrive As Object
With CreateObject("Scripting.FileSystemObject")
For Each objDrive In .Drives
If objDrive.IsReady Then
If objDrive.VolumeName = "VERBATIM HD" Then
destination = objDrive.Path & "\SAUVEGARDE IMPORT\"
Sheets("macros").Range("a203").Value = "SÍ"
Exit For
End If
End If
Next
End With
If Sheets("macros").Range("a203").Value = "" Then
MsgBox "¡El disco duro externo de respaldo no está conectado por USB!", vbCritical
Exit Sub
End If

Dim xlobj As Object
Set xlobj = CreateObject("Scripting.FileSystemObject")
xlobj.CopyFile FolderPath & oFolderItem.Name, destination & oFolderItem.Name, True

Set xlobj = Nothing

End If

End If

Next oFolderItem

If a = "" Then
MsgBox "No hay ninguna etiqueta para la fecha seleccionada el: " & testdate & vbCrLf _
& "Por favor, elige otra fecha", vbCritical
Exit Sub
Else
MsgBox "Se han: " & a & " etiquetas que han sido renombradas el: " & testdate & vbCrLf & _
" sin duplicados y sin las etiquetas que no han sido renombradas."
End If

Dim appShell2 As Object, oFolder2 As Object, oFolderItem2 As Object

FolderPath = "D:\Users\Public\IMPORT\TAGSIMPORTAFAIRE\"
Set appShell2 = CreateObject("Shell.Application")
Set oFolder2 = appShell2.Namespace(FolderPath)

Dim rng As Range, cellul As Range
Set rng = Sheets("archivage").Range("z2:z65000")
For Each cellul In rng
If cellul.Value <> "" Then
On Error GoTo suit
b = b + 1
Dim xlobj2 As Object
Set xlobj2 = CreateObject("Scripting.FileSystemObject")
SetAttr FolderPath & cellul.Value, vbNormal
xlobj2.CopyFile FolderPath & cellul.Value, destination & cellul.Value, True

Set xlobj2 = Nothing
End If
suit::

Next cellul

If b = "" Then
Else
MsgBox "Se han: " & b & " etiquetas que han sido corregidas: " & vbCrLf & _
" y que han sido guardadas en el disco externo."
End If

Sheets("archivage").Range("z2:z65000") = ""
Exit Sub

2 respuestas

  1. ¡Hola!!

    ¡Por favor ayúdame!!! ¡Estoy luchando con este problema de error!!
    ¡Gracias!!
    1. Hola,

      He hecho la búsqueda "VBA error 70" en Google y según Microsoft.
      https://support.microsoft.com/fr-fr/help/147394

      CAUSA
      Este problema ocurre si el archivo fuente que deseas copiar está abierto cuando intentas ejecutar la macro.


      Otro KB que tal vez no tenga relación
      https://support.microsoft.com/fr-fr/help/180384
      El error de ejecución "70" es generalmente el resultado de un problema de seguridad o de permisos. La siguiente lista enumera causas posibles del error de ejecución 70. Sin embargo, no es exhaustiva ni definitiva.

      He estado mirando un poco si hay macros para probar el estado de un archivo.
      Solo veo código para comprobar si un documento de Excel está abierto o no, pero nada para otro tipo de archivo.

      También encontré este sitio: http://www.info-3000.com/vbvba/fichiers/
      Muchos ejemplos de código sobre la copia de archivos y diferentes métodos. Nunca se sabe.

      Desafortunadamente, no soy un super experto en Excel que puede detectar problemas a simple vista. Especialmente porque tu problema puede estar más relacionado con el entorno que con el código. Así que, a menos que logre reproducir el problema en mi ordenador, es difícil poder ayudarte.
      1. Hola,

        Finalmente encontré lo que no funcionaba en mi código:

        Este código:
        Dim objDrive As Object
        With CreateObject("Scripting.FileSystemObject")
        For Each objDrive In .Drives
        If objDrive.IsReady Then
        If objDrive.VolumeName = "VERBATIM HD" Then
        destination = objDrive.Path & "\SAUVEGARDE IMPORT\"

        me daba el error mencionado anteriormente.

        Lo he reemplazado por este que parece funcionar bien:
        Private Declare Function GetVolumeInformation Lib "Kernel32" Alias "GetVolumeInformationA" (ByVal lpRootPathName As String, ByVal lpVolumeNameBuffer As String, ByVal nVolumeNameSize As Long, lpVolumeSerialNumber As Long, lpMaximumComponentLength As Long, lpFileSystemFlags As Long, ByVal lpFileSystemNameBuffer As String, ByVal nFileSystemNameSize As Long) As Long
        Function GetVolumeName(ByVal cDrive As String) As String
        ' http://www.codyx.org/snippet_recuperer-nom-attribue-lecteur-disque-cle-etc_863.aspx
        ' cDrive = CARACTER (letra) de A a Z
        Dim sBuffer As String
        Dim iEnd As Integer

        sBuffer = Space$(255)
        GetVolumeInformation cDrive & ":\", sBuffer, Len(sBuffer), 0&, 0&, 0&, vbNullString, 0&
        iEnd = InStr(1, sBuffer, vbNullChar)
        If iEnd Then GetVolumeName = Left$(sBuffer, iEnd - 1)
        End Function
        Function letraUnidad(nomUnidad As String) As String
        Dim l As Long
        For l = 1 To 26
        If GetVolumeName(Chr(64 + l)) = nomUnidad Then
        letraUnidad = Chr(l + 64)
        Exit For
        End If
        Next l
        End Function

        Dim r As String, nomUnidad As String
        nomUnidad = "VERBATIM HD"
        r = letraUnidad(nomUnidad)
        If r <> "" Then
        Dim destination As String
        destination = r & ":\SAUVEGARDE IMPORT\"
        Else
        MsgBox ("Unidad '" & nomUnidad & "' no encontrada."), vbCritical
        Exit Sub
        End If