Excel开发学习笔记:查找与建立worksheet

开发环境基于VSTO,具体配置:visual studio 2010,VB .Net,excel 2007,文档级别的定制程序。

如题,我在ThisWorkbook.vb中添加了一个public函数来完成查找功能。
函数

入参:待查找的sheet名称spa

返回:若是存在则返回worksheet对象,若是不存在则返回nothing
     Public  Function WorksheetExist(name  As  StringAs Excel.Worksheet  
         Try  
             Dim existSheet  As Excel.Worksheet = Globals.ThisWorkbook.Sheets(name)  
             Return existSheet  
         Catch ex  As Exception  
             Return  Nothing  
         End  Try  
      
     End Function 

 

 

建立worksheet函数,要求在现有sheet的尾部添加新的sheet。

入参:Workbook,新sheet名excel

返回:成功则返回新的sheet对象,失败返回nothingcode

     Private  Function CreatWorksheet( ByRef book  As Excel.Workbook,  ByRef name  As  StringAs Excel.Worksheet  
         Dim newSheet  As Excel.Worksheet = book.Sheets.Add(After:=book.Worksheets(book.Sheets.Count))  
         Try  
      
            newSheet.Name = name  
             Return newSheet  
         Catch ex  As Exception  
             MsgBox( " "" " + name +  " "" " +  " 不能被用做excel工做表(sheet)名称 ")  
            newSheet.Delete()  
             Return  Nothing  
         End  Try  
      
     End Function 

 

 查询与建立连起来使用,未查找到则建立的代码片断:对象

     Dim algoSheet  As Excel.Worksheet = Globals.ThisWorkbook.WorksheetExist(name)  
     If algoSheet  Is  Nothing  Then  
        algoSheet = CreatWorksheet(Globals.ThisWorkbook.Application.Workbooks(Globals.ThisWorkbook.Name), name)  
         If (algoSheet  Is  NothingThen  
             Continue  For  
         End  If  
     End  If 
相关文章
相关标签/搜索