Vb.Net - Excel - Unlock Specific Column

Hi there,

I am trying to Unlock a Specific Column Range in Excel (Column I & J) by using an Invoke Code and I am also running other functions in this same block, like Hiding a specific Column etc.

I am able to Unlock all the Columns using "excelWS.Columns.Locked = False But whenever I try to specify a specific range I am just met with the following Exception

Invoke Code - Format Excel Worksheet: Exception has been thrown by the target of an invocation

This is how my Invoke Code is Setup:

Dim excelWB As Microsoft.Office.Interop.Excel.Workbook
excelApp = New Microsoft.Office.Interop.Excel.ApplicationClass
excelWB = excelApp.Workbooks.Open(excelFilePath)
excelWS = CType(excelWB.Worksheets(excelSheet), Microsoft.Office.Interop.Excel.Worksheet)
'Hide the Column'
excelWS.Range("M:M").EntireColumn.Hidden = True
'Unlock Columns'
'excelWS.Columns.Locked = False'
excelWS.Range("I:J").EntireColumn.Locked = False
excelWB.Save
excelWB.Close
excelApp.Quit

The problem line is the below:

excelWS.Range("I:J").EntireColumn.Locked = False

Any recommendations?

Thanks

Hi Craig, and welcome.

The first thing I’d suggest when debugging these things is to try it on a totally clean file. That should help you identify if the problem is with the file or with the code.
For example if perhaps the worksheet is locked then you cannot change that property whilst the worksheet is locked. Doing it on a blank file (which won’t be locked) can help point you towards things like that, once you figure out the cause it helps to find the solution.

Invoking code is kinda messy in my opinion, so trouble shooting steps like this are the best workaround I can think of right now (please note I avoid invoking code so I am not considering myself an expert on it).