开发者

Excel row locking from .Net

I am generating an Excel spreadsheet from code. I am trying to customize the cells using .net code, and I would like to lock the header row so that it won't allow text to be entered into those cells.

I tries following 2 ways with no success

  1. worksheet.Range("A1", "A1").EntireRow.Locked = True

  2. worksheet.Unprotect()

    worksheet.Range("A1","A100").Locked = True

    worksheet.Protect()

Is that anything I am missing here?

---CODE---

Public Sub CreatNewExcelWithAppliedRules(ByVal noOfWSheets As List(Of String))

    Dim misValue As Object = System.Reflection.Missing.Value
    Dim App As New Application
    Dim workbook As Workbook = App.Workbooks.Add()
    Dim worksheet开发者_StackOverflow中文版 As Worksheet = workbook.Worksheets(1)
    Dim sFile As String = "sample-excel"
    
 
    ---READ HEADERS FROM XML
    Dim xmlFile = "E:\ExcelPOC\ExcelValidation\App_Data\Headers.xml"
    Dim fsReadXml As New System.IO.FileStream(xmlFile, System.IO.FileMode.Open)
    dsHeaders.ReadXml(fsReadXml)
    dtHeader = dsHeaders.Tables("Column")

    ---ADD HEADERS LIST TO EXCEL
    FillColumnHeader(worksheet, dtHeader, culture)

    worksheet.Unprotect()
    ---ADD VALIDATION RULES
    For Each worksheet In workbook.Worksheets
        ListValidExcelRule(worksheet)
        DateValidExcelRule(worksheet)
        TextLengthValidExcelRule(worksheet)
        DecimalValidExcelRule(worksheet)
    Next
    worksheet.Range("1:1").Locked = True
    worksheet.Protect()

    ---SAVE THE EXCEL
     sFile = App.GetSaveAsFilename(InitialFilename:=sFile, FileFilter:="xls Files  (*.xls), *.xls")

    If sFile <> "False" Then
        workbook.SaveAs(Filename:=sFile, _
                              FileFormat:=XlFileFormat.xlWorkbookNormal, _
                              Password:="", _
                              WriteResPassword:="", _
                              ReadOnlyRecommended:=False, _
                              CreateBackup:=False)
    Else
        App.DisplayAlerts = False
    End If

    workbook.Close(True, misValue, misValue)
    App.Quit()
    releaseObject(worksheet)
    releaseObject(workbook)
    releaseObject(App)

End Sub


A1:A100 is the left-hand column. A1:IV1 is the top row. Both of your attempts are close.

Try:

worksheet.Cells.Locked = False
worksheet.Range("1:1").Locked = True
worksheet.Protect

In a new Excel worksheet, all cells are locked by default. Unless you're unlocking the entire worksheet first, you're better off selecting the cells to unlock rather than the cells to lock.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜