1
Set wb = Workbooks(Filename)
Set codeModule = wb.VBProject.VBComponents("ThisWorkbook").codeModule
codeModule.InsertLines 3, "Hej jag kan spara detta"
wb.Save

下面是我的功能。我想解锁 vbaproject 并在 ThisWorkbook 中写入。出于某种原因,当我合并上述 4 行(在 ** 处)时,工作簿未解锁,并且“Hej jag kan spara detta”行未应用于 ThisWorkbook。但是,如果没有这 4 行,工作簿将被解锁。如果工作簿在运行代码之前解锁,同样的 4 行也可以工作。怎么了?

Sub merniplusplus()
    Dim path As String
    Dim Filename As Variant
    Dim wb As Workbook
    Dim CodeModule As Variant

    path = "C:\Merni\"

    Filename = Dir(path & "*.xls")
    Do While Filename <> ""
        If Filename <> "merni.xlsm" Then
            UnprotectPassword Workbooks(Filename), "2lbypo"

            Set wb = ActiveWorkbook
            Set CodeModule = wb.VBProject.VBComponents("ThisWorkbook").CodeModule
            CodeModule.InsertLines 3, "Hej jag kan spara detta"
            wb.Save
        End If
        Filename = Dir()
    Loop
End Sub

Sub UnprotectPassword(wb As Workbook, ByVal projectPassword As String)
    Dim currentActiveWb As Workbook

    If wb.VBProject.Protection <> 1 Then
        Exit Sub
    End If

    wb.Unprotect "poWorkbook"

    Set currentActiveWb = ActiveWorkbook
    wb.Activate

    SendKeys "%{F11}"
    SendKeys "^r" ' Set focus to Explorer
    SendKeys "{TAB}" ' Tab to locked project
    SendKeys "~" ' Enter
    SendKeys projectPassword
    SendKeys "~" ' Enter

    If (wb.VBProject.Protection = vbext_pp_locked) Then
        MsgBox ("failed to unlock")
    End If

    currentActiveWb.Activate
End Sub
4

1 回答 1

1

两件事情

  1. Filename = Dir()应该在循环之前,而不是在这 4 行之前。否则你会得到不一样的Filename

  2. 4行也应该在你的If Filename <> "merni.xlsm" Then 条件内

此外,您可能希望在打开新工作簿之前关闭工作簿。否则你会打开很多工作簿:)

跟进

您没有打开工作簿,而是每次都将其设置为当前工作簿,因此它不起作用。我已经测试了下面的代码,它工作得很好。

Sub merniplusplus()
    Dim path As String, Filename As String
    Dim wb As Workbook
    Dim CodeModule As Variant

    path = "C:\Merni\"

    Filename = Dir(path & "*.xls")

    Do While Filename <> ""
        If Filename <> "merni.xlsm" Then
            Set wb = Workbooks.Open(path & Filename)

            UnprotectPassword wb, "2lbypo"

            Set CodeModule = wb.VBProject.VBComponents("ThisWorkbook").CodeModule
            CodeModule.InsertLines 3, "Hej jag kan spara detta"
            wb.Close SaveChanges:=True
        End If
        Filename = Dir
    Loop
End Sub
于 2012-07-03T12:58:46.143 回答