Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/vba/15.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Excel VBA循环,删除密码,将相同的数据重新保存到每个文件_Excel_Vba_Loops_Passwords - Fatal编程技术网

Excel VBA循环,删除密码,将相同的数据重新保存到每个文件

Excel VBA循环,删除密码,将相同的数据重新保存到每个文件,excel,vba,loops,passwords,Excel,Vba,Loops,Passwords,多亏了这里的一些帮助,我使用下面的VBA代码在xlsx文件目录中循环并删除了已知密码(每个都相同)。但是,下面的代码突然将第一个文件的内容保存到其他文件中。删除密码时,文件夹中的所有文件的内容最终都会被第一个工作簿的内容替换,该工作簿的密码将使用下面的代码删除。密码正在被删除,没有问题,但是每个文件的内容只是被打开的第一个文件的内容覆盖 Public Sub RemovePassLoopThroughFiles() Dim targetWorkbook As Workbook

多亏了这里的一些帮助,我使用下面的VBA代码在xlsx文件目录中循环并删除了已知密码(每个都相同)。但是,下面的代码突然将第一个文件的内容保存到其他文件中。删除密码时,文件夹中的所有文件的内容最终都会被第一个工作簿的内容替换,该工作簿的密码将使用下面的代码删除。密码正在被删除,没有问题,但是每个文件的内容只是被打开的第一个文件的内容覆盖

Public Sub RemovePassLoopThroughFiles()
    
    Dim targetWorkbook As Workbook
    
    Dim filePath As String
    Dim folderPath As String
    Dim folderWildcard As String
    Dim currentFileName As String
    Dim currentFileExtension As String
    Dim newFileName As String
    Dim newfileNameSuffix As String
    Dim currentPassword As String
    Dim newPassword As String
    
    ' Adjust next lines to fit your needs
    
    folderPath = "C:\Temp\" ' With slash at the end
    folderWildcard = "*.xls*" ' You can change the suffix to open specific files
    
    newfileNameSuffix = "_NoPassword"
    
    currentPassword = "pw"
    newPassword = ""
    
    ' Get the file path concat folder and wildcards
    filePath = Dir(folderPath & folderWildcard)
      
    
    Do While Len(filePath) > 0
        ' Open the workbook and set reference
        Set targetWorkbook = Workbooks.Open(Filename:=filePath, Password:=currentPassword)
        
        ' Get current file extension
        currentFileExtension = Right(filePath, Len(filePath) - InStrRev(filePath, "."))
        
        ' Get filename no extension
        currentFileName = Left(filePath, InStrRev(filePath, ".") - 1)
        
        ' Build new fileName
        newFileName = currentFileName & newfileNameSuffix & "." & currentFileExtension
        
        ' Set new password
        targetWorkbook.Password = newPassword
        
        ' Save new file
        targetWorkbook.SaveAs folderPath & newFileName

        'Debug.Print filePath
        
        filePath = Dir

        targetWorkbook.Close True
        
        Set targetWorkbook = Nothing
        
    Loop
    
End Sub

我觉得很好,Excel的哪个版本?@Profex我在Windows上使用Excel 2016。我唯一的想法是,
targetWorkbook
可能没有指向工作簿的savedAs版本,因此它永远不会关闭?@ArcherBird因此,如果我调整代码,在删除密码后只覆盖当前文件,这可能会阻止第一个文件的内容保存到文件夹中的后续文件中?请在
SaveAs
之前和之后添加
Debug.Print targetWorkbook.FullName