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