专注收集记录技术开发学习笔记、技术难点、解决方案
网站信息搜索 >> 请输入关键词:
您当前的位置: 首页 > VB Dotnet

VB2005中把Excel的数据导入Access表取消选择文件操作

发布时间:2011-06-23 14:44:29 文章来源:www.iduyao.cn 采编人员:星星草
VB2005中把Excel的数据导入Access表取消选择文件操作求助
在VB2005中使用下面的语句把Excel中的数据导入到Access中,正常选择Excel文件导入没有问题,但在打开的选择文件窗口中如果选择取消,则系统提示对象错误,意思是没有要导入的文件。请教各位高手,应在下面语句的什么位置上添加什么语句,可以解决已打开选择导入文件窗口后又取消时出现错误提示问题。多谢各位。
Me.OpenFileDialog1.Filter = "Excle文件(*.xls)|*.xls"
If Me.OpenFileDialog1.ShowDialog() = Windows.Forms.DialogResult.OK Then
  'TextBox11.Text = Me.OpenFileDialog1.FileName
  Label11.Text = Me.OpenFileDialog1.FileName
  Dim myDataset As New DataSet
  Dim ExcelConnStr As String = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source='" & Label11.Text & "';Extended 

Properties=Excel 8.0;"
  Dim myDataAdapter As New OleDb.OleDbDataAdapter("SELECT * FROM [Sheet1$]", ExcelConnStr)
  Me.Cursor = Cursors.WaitCursor
  Try
  myDataAdapter.Fill(myDataset) 
  DataGridView2.DataSource = myDataset.Tables(0)
  Catch ex As Exception
  MsgBox(ex.Message)
  Me.Cursor = Cursors.Default
  Exit Sub
  End Try
End If

------解决方案--------------------
Label11.Text = Me.OpenFileDialog1.FileName

只要对这个文件名称作个判断就可以了,如果点了取消,这个 Me.OpenFileDialog1.FileName 就是""空值,所以
if Me.OpenFileDialog1.FileName ="" 的时候 直接exit sub
建议把代码写成 if Me.OpenFileDialog1.FileName <> "" then 写成这种不等于空的判断,有好处,

把你要执行的关键代码全包进这个if里面,当用户点"取消"的时候,根本不会执行的.
------解决方案--------------------
我贴一段我的代码,你看看,我刚才细想了一下,好象不对,我还是把自己用的代码给你,你自己研究吧,
文件名要自己"令"它为空!

Dim strFile As String
Try

If SplitContainer5.Panel1Collapsed = False Then
With SaveFileDialog1
.FileName = " "
.Filter = "Excel文件(*.xls)|*.xls "
.FilterIndex = 1
End With
Else
With SaveFileDialog1
.FileName = " "
.Filter = "Jpeg文件(*.jpg)|*.jpg "
.FilterIndex = 1
End With

End If
If SaveFileDialog1.ShowDialog = Windows.Forms.DialogResult.Cancel Then
strFile = ""
Else
strFile = SaveFileDialog1.FileName
End If

If strFile <> "" Then
Application.DoEvents()

If SplitContainer5.Panel1Collapsed = False Then '导出表格

If C4.Rows.Count = 0 Then
MessageBox.Show("没有记录可以导出", "没有可以导出的项目", MessageBoxButtons.OK, MessageBoxIcon.Information)
Exit Sub
End If



C4.SaveGrid(strFile, FileFormatEnum.Excel, FileFlags.SaveMergedRanges Or FileFlags.IncludeFixedCells)


Dim xlApp As Excel.Application = New Excel.Application

Dim xlBook As Excel.Workbook
Dim xlSheet As Excel.Worksheet

'Set xlApp = Excel.Application
xlApp = CreateObject("excel.application") '不能用上一句,否则excel退不干净

xlApp.Visible = False

xlBook = xlApp.Workbooks.Open(strFile)
xlSheet = xlBook.Worksheets("sheet1")

With xlSheet
.Range(.Cells(1, 1), .Cells(1, C4.Cols.Count)).Font.Name = "微软雅黑"
'设标题为黑体字
'.Range(.Cells(1, 1), .Cells(1, C1.Rows.Count + 2)).Font.Bold = True
友情提示:
信息收集于互联网,如果您发现错误或造成侵权,请及时通知本站更正或删除,具体联系方式见页面底部联系我们,谢谢。

其他相似内容:

热门推荐: