首页 > 其他 > 详细

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

时间:2015-12-09 01:47:50      阅读:248      评论:0      收藏:0      [点我收藏+]
开发环境基于VSTO,具体配置:visual studio 2010,VB .Net,excel 2007,文档级别的定制程序。

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

入参:待查找的sheet名称

返回:如果存在则返回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名

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

    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 

 

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

原文:http://www.cnblogs.com/pop-lar/p/5031524.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!