打开并重用Excel Application的相同实例

时间:2014-03-20 19:44:17

标签: vb.net excel

我想打开一个包含数据的Excel工作簿实例,并允许它保持打开状态但是从视图中隐藏,以便根据用户点击的按钮加载不同的数据。

当前设置: 用户点击“Bird”按钮,打开excel,将#gird加载到VB.NET GUI,关闭excel 用户点击“狗”按钮,打开excel,将#狗加载到VB.NET GUI,关闭excel ...

代码:

Private sub main()

do 
  if(button_dog.clicked = true)
         getdatafromexcel() //gets dog data
  if(button_bird.clicked = true)
         getdatafromexcel() //gets bird data
  if(button_cat.clicked = true)
         getdatafromexcel() //gets cat data
While //User doesn't want to quit
End Main

但是,我无法弄清楚如何设置与Excel工作簿的持续连接,以便它在后台运行,这样每次用户单击其他按钮时我都不必重新打开它。这将大大减少加载和重新加载所需的时间。

您可以使用SQL数据库执行此操作,因此我应该可以使用此excel ...

1 个答案:

答案 0 :(得分:0)

您可以创建Excel应用程序实例,然后隐藏resp。使用Excel Application对象的Application.Visible属性显示它。您可以将应用程序作为参数传递给方法。所以你的代码看起来像这样:

Private sub main()
    'instantiate and open excel for the whole main life time
    Dim excelApplication As Excel.Application = Nothing
    excelApplication = New Excel.Application()

    'hide Excel
    excelApplication.Visible = False
    do 'something excel is still open
      if(button_dog.clicked = true)
             getdatafromexcel(excelApplication) 'gets dog data from excelApplication
      if(button_bird.clicked = true)
             getdatafromexcel() 'gets bird data from excelApplication
      if(button_cat.clicked = true)
             getdatafromexcel() 'gets cat data from excelApplication
    While 'User doesn't want to quit

    ' show Excel if you want to
    excelApplication.Visible = True
    ' close Excel
    excelApplication.Workbooks.Close()
    excelApplication.Quit()
    excelApplication = Nothing

End Main

getdatafromexcel可能如下所示:

Private Sub getdatafromexcel(ByVal excelApp as Excel.Application)
    ' do something with excel
End Sub

您可以为按钮单击创建枚举并重写代码,以便将按钮单击枚举传递给方法 - 这将简化并减少代码(例如,如果在getdatafromexcel方法中做出决定)。

相关问题