AskOverflow.Dev

AskOverflow.Dev Logo AskOverflow.Dev Logo

AskOverflow.Dev Navigation

  • Início
  • system&network
  • Ubuntu
  • Unix
  • DBA
  • Computer
  • Coding
  • LangChain

Mobile menu

Close
  • Início
  • system&network
    • Recentes
    • Highest score
    • tags
  • Ubuntu
    • Recentes
    • Highest score
    • tags
  • Unix
    • Recentes
    • tags
  • DBA
    • Recentes
    • tags
  • Computer
    • Recentes
    • tags
  • Coding
    • Recentes
    • tags
Início / coding / Perguntas / 78992594
Accepted
Forward Ed
Forward Ed
Asked: 2024-09-17 13:06:46 +0800 CST2024-09-17 13:06:46 +0800 CST 2024-09-17 13:06:46 +0800 CST

Método alternativo para excluir arquivo sem ter que adicionar MS Scripting Runtime Reference

  • 772

A resposta a esta pergunta afirma que para evitar o erro você precisa adicionar a referência a MS Scripting Run-time.

Usei essa metodologia para excluir um arquivo no meu código, mas como sei que ele será usado em vários computadores que não terão essa referência incluída, acho que tenho duas opções:

  1. Use uma metodologia diferente para excluir um arquivo existente.
  2. Descubra uma maneira de carregar o arquivo de referência quando o arquivo for aberto.

Este sub está vinculado a um botão ActiveX na planilha

Sub Createbackupfile()

Dim strCurrentName As String
Dim strCurrentPathAndName As String
Dim strCurrentPath As String
Dim strPreviousFilename As String

    strCurrentName = ThisWorkbook.Name
    strCurrentPathAndName = ThisWorkbook.FullName
    strCurrentPath = Replace(strCurrentPathAndName, strCurrentName, "")
    
    NewPath = "OldForecasts\"
    
    With ThisWorkbook
        .SaveAs Filename:=strCurrentPath & StrNewPath & strCurrentName, FileFormat:=xlOpenXMLWorkbookMacroEnabled, CreateBackup:=False
    End With
    
    With New FileSystemObject
        If .FileExists(CurrentPathAndName) Then
            .deleteFile CurrentPathAndName
        End If
    End With
    
End Sub

Pergunta

O que é uma abordagem alternativa ao usoNew FileSytemObject

excel
  • 2 2 respostas
  • 50 Views

2 respostas

  • Voted
  1. Best Answer
    FunThomas
    2024-09-17T15:39:14+08:002024-09-17T15:39:14+08:00

    Algumas coisas a mencionar:

    (1) Uma pequena coisa: Você pode acessar a pasta de uma pasta de trabalho usando ThisWorkbook.Path(note que isso não contém a barra invertida final). Então use strCurrentPath = ThisWorkbook.Path

    (2) Você atribui o nome da subpasta a uma variável chamada NewPathmas depois você acessa strNewPath. O mesmo problema com CurrentPathAndNamevs strCurrentPathAndName. Evite tais erros usando sempre Option Explicit.

    Além disso, a menos que em seu código você planeje ter diferentes subpastas como pasta de backup, declare o novo caminho como constante, não como variável:

    Const strNewPath = "OldForecasts"
    

    (3) Conforme mencionado nos comentários, existem alguns comandos (bastante antigos) para manipulação de arquivos no VBA:

    killpara apagar um arquivo
    Dirpara verificar se um arquivo ou pasta existe. Para verificar pastas, você precisa adicionar vbDirectorycomo 2º argumento ao Dir-command.
    MkDirpara criar uma pasta.

    O código poderia ser parecido com este:

    Option Explicit
    
    Sub Createbackupfile()
    
        Const BackupFolder = "OldForecasts"
    
        Dim CurrentName As String
        Dim CurrentPathAndName As String
        Dim CurrentPath As String
    
        With ThisWorkbook
            CurrentName = .Name
            CurrentPathAndName = .FullName
            CurrentPath = .Name
    
            Dim newPath As String
            newPath = CurrentPath & "\" & BackupFolder
            If Dir(newPath, vbDirectory) = "" Then MkDir newPath
            .SaveAs Filename:=newPath & "\" & CurrentName, FileFormat:=xlOpenXMLWorkbookMacroEnabled, CreateBackup:=False
            Kill CurrentPathAndName
        End With
    End Sub
    

    Observe que se esse código também for executado em um Mac, você precisará substituir a barra invertida por uma barra - ou usar Application.PathSeparator:

    newPath = CurrentPath & Application.PathSeparator & BackupFolder
    

    (até onde eu sei, os comandos em si funcionam em um Mac, mas não posso verificar isso porque não tenho um Mac para testar.)

    (4) O FileSystemObjectScripting Runtime é uma forma alternativa de acessar informações de arquivos e pastas. Ele tem algumas vantagens sobre os comandos antigos (por exemplo, você pode percorrer recursivamente suas pastas e subpastas) e oferece comandos adicionais.

    O Scripting Runtime está presente em todos os computadores Windows (mas não em nenhum Mac). Adicionar uma referência ao seu projeto apenas informa ao compilador VBA que você quer usá-lo (isso é chamado de early binding ). A vantagem é que o compilador pode verificar a sintaxe para você já no momento da compilação, e você tem o intellisense como suporte ao digitar o código.

    No entanto, você pode viver perfeitamente sem vinculação antecipada usando CreateObject. Isso é chamado de vinculação tardia . O compilador não sabe nada sobre o objeto que é criado e, se você acessar qualquer propriedade ou método, o tempo de execução do VBA examinará o tempo de execução, se existir. Exemplo:

    ' Early binding (your current code)
    With New FileSystemObject
        If .FileExists(CurrentPathAndName) Then
            .DeleteFile CurrentPathAndName
        End If
    End With
    

    O editor VBA pode ajudar você com o intellisense e o compilador verifica se os métodos FileExistse DeleteFileexistem. Se você tiver um erro de digitação (você digita por exemplo FileExist), o compilador já pode avisá-lo antes que o código seja executado.

    ' Late binding (no reference needed) 
    With CreateObject("Scripting.FileSystemObject")
        If .FileExists(CurrentPathAndName) Then
            .DeleteFile CurrentPathAndName
        End If
    End With
    

    Agora o compilador não sabe nada sobre o objeto criado e você receberá um erro de tempo de execução ao usar um nome de método inválido.

    Ambas as versões funcionarão em qualquer computador onde a biblioteca exista e não funcionarão em nenhum computador onde a biblioteca não exista. No entanto, quando a biblioteca não existe e você usa a vinculação antecipada, o código não será compilado e você não poderá usar nenhum código. Com a vinculação tardia, você pode usar qualquer outro código do seu projeto.

    • 2
  2. VBasic2008
    2024-09-17T18:03:45+08:002024-09-17T18:03:45+08:00

    Mover a pasta de trabalho que contém o código para uma subpasta específica

    Uma Chamada Simples

    Sub MoveToOldForecasts()
        MoveFileToSubfolder ThisWorkbook, "OldForecasts"
    End Sub
    

    Uma ferramenta

    Sub MoveFileToSubfolderRun()
        Dim SubfolderName  As String: SubfolderName = InputBox( _
            Prompt:="Please enter the name of the subfolder", _
            Title:="Move File to Subfolder", _
            Default:="Subfolder Name")
        MoveFileToSubfolder ThisWorkbook, SubfolderName
    End Sub
    

    O Método

    Sub MoveFileToSubfolder(ByVal wb As Workbook, ByVal SubfolderName As String)
        Const PROC_TITLE As String = "Move File to Subfolder"
        On Error GoTo ClearError
    
        ' Check if no workbook was passed.
        If wb Is Nothing Then
            MsgBox "The workbook was not referenced!", vbExclamation, PROC_TITLE
            Exit Sub
        End If
         
        ' Check if the subfolder name was not supplied.
        If Len(SubfolderName) = 0 Then
            MsgBox "No subfolder supplied!", vbExclamation, PROC_TITLE
            Exit Sub
        End If
        
        ' Retrieve the source file name.
        Dim sFileName As String: sFileName = wb.Name
    
        ' Retrieve the source path.
        Dim sFolderPath As String: sFolderPath = wb.Path
        ' Check if the source file has no path.
        If Len(sFolderPath) = 0 Then
            MsgBox "The file """ & sFileName & """ was never saved!", _
                vbExclamation, PROC_TITLE
            Exit Sub
        End If
            
        ' Create/reference an instance of the 'Scripting FileSystemObject' object.
        Dim fso As Object: Set fso = CreateObject("Scripting.FileSystemObject")
        
        ' Build the destination file path.
        Dim dFolderPath As String:
        dFolderPath = fso.BuildPath(sFolderPath, SubfolderName)
        
        ' Create the destination folder.
        If Not fso.FolderExists(dFolderPath) Then
            On Error Resume Next
                fso.CreateFolder dFolderPath
            On Error GoTo ClearError
            ' Check if the destination folder was not created.
            If Not fso.FolderExists(dFolderPath) Then
                MsgBox "Could not create the folder """ & SubfolderName _
                    & """ in """ & sFolderPath & """.", _
                    vbExclamation, PROC_TITLE
                Exit Sub
            End If
        End If
        
        ' Build the destination file name and path.
        Dim dFileName As String: dFileName = fso.GetBaseName(sFileName) & ".xlsm"
        Dim dFilePath As String: dFilePath = fso.BuildPath(dFolderPath, dFileName)
        ' Note: Why not simply 'dFilePath = fso.BuildPath(dFilePath, sFileName)'?
        '       Because 'ThisWorkbook' could be e.g. a '.xls' or '.xlsb' file.
        '       It could even be e.g. a '.xlsx' file where the code
        '       was copied to.
            
        ' Retrieve the source file path.
        Dim sFilePath As String: sFilePath = wb.FullName
            
        ' Save the file to the destination folder.
        On Error Resume Next
            Application.DisplayAlerts = False
            ' The line above enables overwriting with no confirmation and prevents
            ' the appearance of the dialog when saving in a different file format.
                wb.SaveAs Filename:=dFilePath, _
                    FileFormat:=xlOpenXMLWorkbookMacroEnabled, CreateBackup:=False
            Application.DisplayAlerts = True
        On Error GoTo ClearError
        ' Check if the file was not saved.
        If Not fso.FileExists(dFilePath) Then
            MsgBox "Could not save the file as """ & dFilePath & """!", _
                vbExclamation, PROC_TITLE
            Exit Sub
        End If
        ' Note: At this point the 'wb' variable points to the destination file.
        Debug.Print wb.Name, wb.Path ' the proof
        
        ' Delete the source file.
        On Error Resume Next
            fso.GetFile(sFilePath).Delete
        On Error GoTo ClearError
        ' Check if the source file was not deleted.
        Dim WasSourceDeleted As Boolean: WasSourceDeleted = True
        If fso.FileExists(sFilePath) Then WasSourceDeleted = False
        
        ' Inform.
        If WasSourceDeleted Then
            MsgBox "The file" & vbLf & vbLf & """" & sFilePath & """" & vbLf _
                & "was moved to" & vbLf & vbLf & """" & dFilePath & """.", _
                vbInformation, PROC_TITLE
        Else
            MsgBox "The file" & vbLf & vbLf & """" & sFilePath & """" & vbLf _
                & "was moved to" & vbLf & vbLf & """" & dFilePath & """." _
                & vbLf & vbLf & "Could not delete the source file """ & sFilePath _
                & """!", vbExclamation, PROC_TITLE
        End If
        
    ProcExit:
        Exit Sub
    ClearError:
        MsgBox "Run-time error [" & Err.Number & "]:" & vbLf & vbLf _
            & Err.Description, vbCritical, PROC_TITLE
        Resume ProcExit
    End Sub
    
    • 1

relate perguntas

  • Como posso retornar linhas específicas onde EXISTE uma taxa no contrato listado, mas NÃO há taxa no sistema?

  • adicionar automaticamente um campo de referência em uma tabela quando alguns valores são repetidos?

  • percorrer a coluna com a alteração do endereço da célula

  • Pesquise uma string e os valores de saída correspondentes a essa string

  • Existe uma maneira no Excel de contar as ocorrências de um texto específico em uma string, mas também incluir o caractere anterior?

Sidebar

Stats

  • Perguntas 205573
  • respostas 270741
  • best respostas 135370
  • utilizador 68524
  • Highest score
  • respostas
  • Marko Smith

    Vue 3: Erro na criação "Identificador esperado, mas encontrado 'import'" [duplicado]

    • 1 respostas
  • Marko Smith

    Por que esse código Java simples e pequeno roda 30x mais rápido em todas as JVMs Graal, mas não em nenhuma JVM Oracle?

    • 1 respostas
  • Marko Smith

    Qual é o propósito de `enum class` com um tipo subjacente especificado, mas sem enumeradores?

    • 1 respostas
  • Marko Smith

    Como faço para corrigir um erro MODULE_NOT_FOUND para um módulo que não importei manualmente?

    • 6 respostas
  • Marko Smith

    `(expression, lvalue) = rvalue` é uma atribuição válida em C ou C++? Por que alguns compiladores aceitam/rejeitam isso?

    • 3 respostas
  • Marko Smith

    Quando devo usar um std::inplace_vector em vez de um std::vector?

    • 3 respostas
  • Marko Smith

    Um programa vazio que não faz nada em C++ precisa de um heap de 204 KB, mas não em C

    • 1 respostas
  • Marko Smith

    PowerBI atualmente quebrado com BigQuery: problema de driver Simba com atualização do Windows

    • 2 respostas
  • Marko Smith

    AdMob: MobileAds.initialize() - "java.lang.Integer não pode ser convertido em java.lang.String" para alguns dispositivos

    • 1 respostas
  • Marko Smith

    Estou tentando fazer o jogo pacman usando apenas o módulo Turtle Random e Math

    • 1 respostas
  • Martin Hope
    Aleksandr Dubinsky Por que a correspondência de padrões com o switch no InetAddress falha com 'não cobre todos os valores de entrada possíveis'? 2024-12-23 06:56:21 +0800 CST
  • Martin Hope
    Phillip Borge Por que esse código Java simples e pequeno roda 30x mais rápido em todas as JVMs Graal, mas não em nenhuma JVM Oracle? 2024-12-12 20:46:46 +0800 CST
  • Martin Hope
    Oodini Qual é o propósito de `enum class` com um tipo subjacente especificado, mas sem enumeradores? 2024-12-12 06:27:11 +0800 CST
  • Martin Hope
    sleeptightAnsiC `(expression, lvalue) = rvalue` é uma atribuição válida em C ou C++? Por que alguns compiladores aceitam/rejeitam isso? 2024-11-09 07:18:53 +0800 CST
  • Martin Hope
    The Mad Gamer Quando devo usar um std::inplace_vector em vez de um std::vector? 2024-10-29 23:01:00 +0800 CST
  • Martin Hope
    Chad Feller O ponto e vírgula agora é opcional em condicionais bash com [[ .. ]] na versão 5.2? 2024-10-21 05:50:33 +0800 CST
  • Martin Hope
    Wrench Por que um traço duplo (--) faz com que esta cláusula MariaDB seja avaliada como verdadeira? 2024-05-05 13:37:20 +0800 CST
  • Martin Hope
    Waket Zheng Por que `dict(id=1, **{'id': 2})` às vezes gera `KeyError: 'id'` em vez de um TypeError? 2024-05-04 14:19:19 +0800 CST
  • Martin Hope
    user924 AdMob: MobileAds.initialize() - "java.lang.Integer não pode ser convertido em java.lang.String" para alguns dispositivos 2024-03-20 03:12:31 +0800 CST
  • Martin Hope
    MarkB Por que o GCC gera código que executa condicionalmente uma implementação SIMD? 2024-02-17 06:17:14 +0800 CST

Hot tag

python javascript c++ c# java typescript sql reactjs html

Explore

  • Início
  • Perguntas
    • Recentes
    • Highest score
  • tag
  • help

Footer

AskOverflow.Dev

About Us

  • About Us
  • Contact Us

Legal Stuff

  • Privacy Policy

Language

  • Pt
  • Server
  • Unix

© 2023 AskOverflow.DEV All Rights Reserve