Verificar si un libro existe

Estoy tratando de verificar si un libro existe y si este existe que le cambie el nombre, el cambio de nombre funciona bien pero cuando trato de verificar si el libro existe me sale error 24, en esta linea

If My.Computer.FileSystem.File.Exists(NombreRuta) Then

Estas son las lineas que estoy usando.

Gracias por la ayuda.

Sub CambiarNombres()
Dim NombreViejo As String
Dim NombreViejo1 As String
Dim NombreNuevo As String
Dim NombreNuevo1 As String
Dim NombreRuta As String
ruta = "C:\Aloha\pedidos\"
nombre = Format(Now, "ddmmyyyy")
extencion = ".pdf"
NombreRuta = ruta & nombre & extencion
If My.Computer.FileSystem.File.Exists(NombreRuta) Then
For Each fichero In Range("A2:A2")
NombreViejo = "C:\Aloha\pedidos\" & fichero.Value & ".xlsx"
NombreViejo1 = "C:\Aloha\pedidos\" & fichero.Value & ".pdf"
NombreNuevo = "C:\Aloha\pedidos\" & fichero.Offset(0, 1).Value & ".xlsx"
NombreNuevo1 = "C:\Aloha\pedidos\" & fichero.Offset(0, 1).Value & ".pdf"
Name NombreViejo As NombreNuevo
Name NombreViejo1 As NombreNuevo1
Next fichero
Else
End If
End Sub

Respuesta
1

Este ejemplo

http://www.programarexcel.com/2014/04/verifica-si-existe-libro-y-crea-libro.html 

1 respuesta más de otro experto

Respuesta
3

Prueba con la siguiente:

Sub CambiarNombres()
    Dim NombreViejo As String, NombreViejo1 As String
    Dim NombreNuevo As String, NombreNuevo1 As String
    Dim ruta As String
    ruta = "C:\Aloha\pedidos\"
    'ruta = ThisWorkbook.Path & "\"
    For Each fichero In Range("A2:A2")
        NombreViejo = ruta & fichero.Value & ".xlsx"
        NombreViejo1 = ruta & fichero.Value & ".pdf"
        NombreNuevo = ruta & fichero.Offset(0, 1).Value & ".xlsx"
        NombreNuevo1 = ruta & fichero.Offset(0, 1).Value & ".pdf"
        If Dir(NombreViejo) <> "" Then
            Name NombreViejo As NombreNuevo
        End If
        If Dir(NombreViejo1) <> "" Then
            Name NombreViejo1 As NombreNuevo1
        End If
    Next fichero
End Sub

En VBA no es necesario declarar todas las variable, además creo que se podría simplificar si utilizas directamente el dato de la celda, por ejemplo:

Sub CambiarNombres2()
    ruta = "C:\Aloha\pedidos\"
    For Each fichero In Range("A2:A2")
        If Dir(ruta & fichero.Value & ".xlsx") <> "" Then
            Name ruta & fichero.Value & ".xlsx" As ruta & fichero.Offset(0, 1).Value & ".xlsx"
        End If
        If Dir(ruta & fichero.Value & ".pdf") <> "" Then
            Name ruta & fichero.Value & ".pdf" As ruta & fichero.Offset(0, 1).Value & ".pdf"
        End If
    Next fichero
End Sub

'S aludos. Dante Amor. Recuerda valorar la respuesta. G racias

Añade tu respuesta

Haz clic para o

Más respuestas relacionadas