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
答案 0 :(得分:1)
两件事
Filename = Dir()
应该在循环之前而不是在那4行之前。否则,您将获得不同的Filename
。
此外,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