Excel and VBA: Update protected fields on button press
I have an excel document that queries an SQL Database on button press. The document needs to be read-only. Currently, with the fields locked, on button press I receive the following run time error:
Run-time error '1004':
The cell or chart that you are trying to change is protected and therefore read-only.
I've done some searching and I can find some ways to open read-only/password protected files, but not how to apply changes to the protected rows while the file is read-only.
This is the code I currently have at the beginning of the module:
Sub Update()
Application.Calculation = xlCalculationManual
Dim Cnn As Object
Dim rstTmp As Object
Dim appExcel As Excel.Application
Dim wbkReport As Excel.Workbook
Dim wksReport As Excel.Worksheet
Set Cnn = CreateObject("ADODB.Connection")
Set rstTmp = CreateObject("ADODB.Recordset")
Cnn.Open "Driver={SQL Server};Server=IPHERE;;UID=NOPE;PWD=ALMOST;DATABASE=DB;Trusted_Connection=No"
I'm trying to "reverse engineer" this functionality into a current excel. I have little to no experience with this so开发者_如何学运维 I am just jumping headlong into the deep end.
If any additional information is needed, I will be happy to add it.
Thanks in advance!
Use the following:
Private Sub Workbook_Open()
Dim wSheet As Worksheet
For Each wSheet In Worksheets
wSheet.Protect UserInterFaceOnly:=True
Next wSheet
End Sub
This will lock all sheets in the user interface, but allow scripts to modify anything. You should put it in the load script for the book, because closing the program and reopening it will cause the protection to revert to full protection again. So it must be run every time the file opens.
精彩评论