Reputation: 161
Following is my C# code,where i`m trying to unlock protected sheet by passing password,but it still not unlocking the sheet, I need to add some macro to the sheet .
Code:
const string excelFile = @"c:\temp\VBA\test.xlsm";
var excelApplication = new ExcelInterop.Application { Visible = true };
var targetExcelFile = excelApplication.Workbooks.Open(FileName:excelFile,Password:"12asQOl");
I can`t use "sendKeys" here,please help me on this.
Thanks
Upvotes: 2
Views: 7185
Reputation: 165
In your code you are passing the document password. You are not un-protecting the workbook.
Use the following code to un-protect the workbook:
targetExcelFile.Unprotect(password);
Let me know if you have any issues.
Upvotes: 1
Reputation: 5777
One piece of advice when working with VBA: start recording a macro of what you're trying to do then see the generated code.
Looks like you're trying to open a protected file, not unprotect a sheet.
I've found some old code of something like this (it's VB):
Dim WSheet As Worksheet
For Each WSheet In Worksheets
If WSheet.ProtectContents = True Then
WSheet.Unprotect Password:=MyPassword
Else
WSheet.Protect Password:=MyPassword
End If
Next WSheet
Upvotes: 1