VB to insert a row in a password protected book

lbradbury

New Member
Joined
May 14, 2020
Messages
46
Office Version
  1. 365
Platform
  1. Windows
Hello,

I have this code, so simply add a line when a object button is pushed. However, I want to password protect the sheet, and naturally this vba does not work then. How do I write in a code that will allow for the rows to be inserted?

VBA Code:
Sub addline()
'
    Rows("23:23").Select
    Selection.Copy
    Rows("24:24").Select
    Selection.Insert Shift:=xlDown
End Sub
 

Excel Facts

What do {} around a formula in the formula bar mean?
{Formula} means the formula was entered using Ctrl+Shift+Enter signifying an old-style array formula.
VBA Code:
Sub addline()

Sheets("Sheet1").UnProtect Password:="myPassword"

    Rows("23:23").Select
    Selection.Copy
    Rows("24:24").Select
    Selection.Insert Shift:=xlDown

Sheets("Sheet1").Protect Password:="myPassword"

End Sub
 
Upvote 0
- If your current code is working (apart from the sheet protection) then you don't need to specify the sheet name. The advantage of that is the code would still work even if the sheet name gets changed.
- Selecting in vba is rarely required and can slow your code.
- When inserting a whole row there is no need to specify to shift the others down as there is no other way for them to go. :)
- No need to double-up the row numbers or use quote marks in this case.

So an alternative is
VBA Code:
Sub addline()
  With ActiveSheet
    .Unprotect Password:="myPassword"
    .Rows(23).Copy
    .Rows(24).Insert
    .Protect Password:="myPassword"
  End With
End Sub
 
Upvote 0

Forum statistics

Threads
1,215,215
Messages
6,123,668
Members
449,114
Latest member
aides

We've detected that you are using an adblocker.

We have a great community of people providing Excel help here, but the hosting costs are enormous. You can help keep this site running by allowing ads on MrExcel.com.
Allow Ads at MrExcel

Which adblocker are you using?

Disable AdBlock

Follow these easy steps to disable AdBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the icon in the browser’s toolbar.
2)Click on the "Pause on this site" option.
Go back

Disable AdBlock Plus

Follow these easy steps to disable AdBlock Plus

1)Click on the icon in the browser’s toolbar.
2)Click on the toggle to disable it for "mrexcel.com".
Go back

Disable uBlock Origin

Follow these easy steps to disable uBlock Origin

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back

Disable uBlock

Follow these easy steps to disable uBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back
Back
Top