自动执行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.