Este fórum está sendo desativado

Depois de 9 anos, este fórum será desativado. Mas calma.... estamos migrando para uma comunidade no DISCORD. Junte-se a nós.

ENTRAR PARA DISCORD

Tópicos relacionados a códigos VBA, gravação de macros, etc.
  • Avatar do usuário
Por Diego100ges
Posts
#51108
Prezados boa tarde!
Estou com um código aqui para salvar a folha do Excel aberta em PDF, e ele funciona perfeitamente, porém se eu quiser salvar novamente ele e o arquivo PDF estiver aberto ele não salva, o que é obvio, visto que ele salva substituindo o arquivo antigo, e é exatamente isso que eu quero, meu problema é o seguinte, quando ele não salva porque o arquivo esta aberto o vba apresenta o erro, e trava o código, eu não gostaria que ele travasse o código, somente me avisasse por meio de uma MsgBox que o arquivo gerado anteriormente ainda está aberto e por isso não foi possível executar a macro.

Mas não estou conseguindo fazer isso com o On Erro GoTo, gostaria de algumas opiniões.

Segue o código:
Código: Selecionar todos
Sub TestePdf()
On Erro GoTo Erro

   Dim PdfCaminho As String
    Dim PdfNome As String
  
    PdfCaminho = VBA.Environ("USERPROFILE") & "\Desktop\"
    PdfNome = "Cotações" & " " & Range("B8").Value
    
  MsgBox "O arquivo " & PdfNome & " foi salvo em " & PdfCaminho & ".", vbOKOnly, "Salvo"

    ThisWorkbook.ActiveSheet.ExportAsFixedFormat Type:=xlTypePDF, Filename:= _
    PdfCaminho & PdfNome, Quality:= _
    xlQualityStandard, IncludeDocProperties:=True, IgnorePrintAreas:=False, _
    OpenAfterPublish:=True
    
Exit Sub
Erro: MsgBox ("teste")
    
End Sub

Avatar do usuário
Por Basole
Posts Avatar
#51109
Veja este exemplo de funcao que verifica se o arquvo esta aberto
..sua macro com a checagem:
Código: Selecionar todos
Sub TestePdf()
On Erro GoTo Erro

   Dim PdfCaminho As String
    Dim PdfNome As String
 
    PdfCaminho = VBA.Environ("USERPROFILE") & "\Desktop\"
    PdfNome = "Cotações" & " " & Range("B8").Value
     
   If Not IsFileOpen(PdfCaminho & PdfNome) Then '~~> chama a funcao

    ThisWorkbook.ActiveSheet.ExportAsFixedFormat Type:=xlTypePDF, FileName:= _
    PdfCaminho & PdfNome, Quality:= _
    xlQualityStandard, IncludeDocProperties:=True, IgnorePrintAreas:=False, _
    OpenAfterPublish:=True
    
    MsgBox "O arquivo " & PdfNome & " foi salvo em " & PdfCaminho & ".", vbOKOnly, "Salvo"
  Else
    MsgBox "...o arquivo gerado anteriormente ainda está aberto e " & _
                "por isso não foi possível executar a macro.", 16, ("teste")
  End If
Exit Sub

Erro: MsgBox ("teste")
   
End Sub
..e a funcao...
Código: Selecionar todos
Function IsFileOpen(FileName As String)
    Dim ff As Long, ErrNo As Long

    On Error Resume Next
    ff = FreeFile()
    Open FileName For Input Lock Read As #ff
    Close ff
    ErrNo = Err
    On Error GoTo 0

    Select Case ErrNo
    Case 0:    IsFileOpen = False
    Case 70:   IsFileOpen = True
    Case Else: Error ErrNo
    End Select
End Function
fonte: https://stackoverflow.com/a/9373914
Por Diego100ges
Posts
#51170
Continua dando o mesmo problema,
Código: Selecionar todos
    ThisWorkbook.ActiveSheet.ExportAsFixedFormat Type:=xlTypePDF, FileName:= _
    PdfCaminho & PdfNome, Quality:= _
    xlQualityStandard, IncludeDocProperties:=True, IgnorePrintAreas:=False, _
    OpenAfterPublish:=True
Ele ignora o If Not IsFileOpen, e executa essa linha acima que salva o PDF.
long long title how many chars? lets see 123 ok more? yes 60

We have created lots of YouTube videos just so you can achieve [...]

Another post test yes yes yes or no, maybe ni? :-/

The best flat phpBB theme around. Period. Fine craftmanship and [...]

Do you need a super MOD? Well here it is. chew on this

All you need is right here. Content tag, SEO, listing, Pizza and spaghetti [...]

Lasagna on me this time ok? I got plenty of cash

this should be fantastic. but what about links,images, bbcodes etc etc? [...]

Estamos migrando para uma comunidade no Discord