自动执行OpenFIleDialog以在没有用户输入的情况下打开文件 [英] Automating OpenFIleDialog to Open a file without user input

查看:91
本文介绍了自动执行OpenFIleDialog以在没有用户输入的情况下打开文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

您好我在vb.net中有一个Windows窗体程序,它使用数据网格来提取数据集(excel)并显示其内容。现在,我无法设置刷新,只需按一下按钮即可动态更新数据集。我认为我可能这样做的唯一方法是自动化Excel关闭然后打开文件,而无需用户进行打开的对话框控制。我怎样才能自动执行代码来实现这一目标?非常感谢您提供的任何帮助。



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.

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

推荐答案

取出OpenFileDialog代码并将其放入单独的方法中。所有OFD都会显示一个对话框并返回一个包含用户选择的文件路径的字符串。



如果你已经在一个字符串中有文件路径,那么将它传递给一个执行打开文件并获取内容的方法,然后关闭文件。
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.


这篇关于自动执行OpenFIleDialog以在没有用户输入的情况下打开文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆