Click here to Skip to main content
15,891,629 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
Hello I have a windows forms program in vb.net that uses a datagrid to pull a dataset (excel) and display its contents. Right now I'm having trouble setting up a refresh that will dynamically update the dataset by pressing a button. The only way I think I might do this is to automate Excel to close and then open up the file without the user having to go through an open dialog control. How might I be able to automate my code to achieve this? I greatly appreciate any help you may offer.

VB
Sub refreshDataSet()
        Try
            Cursor.Current = Cursors.WaitCursor
            Write2myExcel()
        Finally
            Cursor.Current = Cursors.Default
        End Try

        closexlsfile()

        If openExcelfile(txtFilePath.Text) Then
            Try
                Cursor.Current = Cursors.WaitCursor
                RetrieveExcel()
                ValidateExcel()
            Finally
                Cursor.Current = Cursors.Default
            End Try
            Me.btnBrowse.Enabled = False
        End If

End Sub
         Function openExcelfile(programmedfilename as string) As Boolean


        openExcelfile = False


        If programmedfilename <> "" Then
            Dim dlg As New OpenFileDialog()
            dlg.Filter = "Excel Macro Enabled Files|*.xlsm*|Excel Files|*.xls|Excel 2007 Files|*.xlsx|All Files|*.*"
            If dlg.ShowDialog() = DialogResult.OK Then


                txtFilePath.Text = dlg.FileName

            End If
        Else
            txtFilePath.Text = programmedfilename
        End If

        Me.ExcelWriteBtn.Enabled = txtFilePath.Text.Length > 0
        Me.closexlsbtn.Enabled = txtFilePath.Text.Length > 0




        Dim ExcelSheetName As String = ""

        objExcel = CreateObject("Excel.Application")

        wrkbks = objExcel.Workbooks
        objworkbook = wrkbks.Open(programmedfilename)


        openExcelfile = True


    End Function
Posted
Updated 7-Sep-13 4:41am
v2
Comments
[no name] 7-Sep-13 10:48am    
Well it's pretty simple. If you do not need or want the user input, then stop asking for it.

1 solution

Take the OpenFileDialog code out and put it into a separate method. All the OFD does is show a dialog and return a string containing the filepath picked by the user.

If you already have the filepath in a string, pass that to a method that does the job of opening the file and grab the contents, then close the file.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900