C#excel隐藏和locking行

最近我已经把一个项目从VBA转换到C#,但是我遇到了.Hidden(),.Locked()和.Protect()

在VBA实现中,如果我隐藏(行) – >锁 – >保护,那么我不能取消隐藏行(如预期),但在C#实现中,如果我隐藏(行) – >锁 – >保护行可以被隐藏突出显示行,右键单击,取消隐藏)

是否有我缺less的东西,还是有不同的方式,需要编写的C#版本产生相同的结果(行不能被隐藏)为VBA版本?

我已经简化了代码到这些简短的片段,重现结果。 这两个版本都创build一个新的工作簿,修改一个单元格,隐藏locking保护行,并保存/closures工作簿。

C#版本:

using Excel = Microsoft.Office.Interop.Excel; ... private void button1_Click(object sender, EventArgs e) { Excel.Application ex = new Excel.Application(); Excel.Workbooks Books = ex.Workbooks; //create and save the output workbook (so only .save() needs to be called later) Excel.Workbook OutputBook = Books.Add(); OutputBook.SaveAs("C:\\TestingFolder\\Outputbook.xlsm", Excel.XlFileFormat.xlOpenXMLWorkbookMacroEnabled); //write secret stuff OutputBook.Sheets[1].Cells[15,15] = "Stuff"; //hide and lock rows around secret stuff OutputBook.Sheets[1].Range["10:20"].EntireRow.Hidden = true; OutputBook.Sheets[1].Range["10:20"].EntireRow.Locked = true; //protect the sheet with a bad password OutputBook.Sheets[1].Protect( "SomePassword123",//password false, //drawing objects true, //Contents false, //scenarios false, //user interface true, //format cells true, //format columns true, //format rows false, //insert columns false, //insert rows true, //insert hyperlinks false, //delete columns false, //delete rows true, //allow sorting true, //allow filtering true //allow pivot tables ); //save and close output workbook OutputBook.Save(); OutputBook.Close(false); //-----general cleanup start----- Books.Close(); ex.Quit(); System.Runtime.InteropServices.Marshal.ReleaseComObject(OutputBook); System.Runtime.InteropServices.Marshal.ReleaseComObject(Books); System.Runtime.InteropServices.Marshal.ReleaseComObject(ex); OutputBook = null; Books = null; ex = null; GC.Collect(); //-----general cleanup end----- //show message that the task completed MessageBox.Show("done"); } 

和VBA版本:

 Private Sub CommandButton1_Click() 'create and save the output workbook (so only .save() needs to be called later) Dim OutputBook As Workbook Set OutputBook = Workbooks.Add Call OutputBook.SaveAs("C:\TestingFolder\Outputbook.xlsm", ThisWorkbook.FileFormat) 'write secret stuff OutputBook.Sheets(1).Cells(15, 15) = "Stuff" 'hide and lock rows around secret stuff OutputBook.Sheets(1).Range("10:20").EntireRow.Hidden = True OutputBook.Sheets(1).Range("10:20").EntireRow.Locked = True 'protect the sheet with a bad password OutputBook.Sheets(1).Protect Password:="SomePassword123", _ DrawingObjects:=False, _ Contents:=True, _ Scenarios:=False, _ AllowFormattingCells:=True, _ AllowInsertingHyperlinks:=True, _ AllowSorting:=True, _ AllowFiltering:=True, _ AllowUsingPivotTables:=True 'save and close output workbook Call OutputBook.Save Call OutputBook.Close 'show message that the task completed MsgBox "done" End Sub 

在您的Protect方法中,格式rows参数必须设置为false而不是true