VB6.0 读取Excel2010简单方法(附源码和注释,可伸手)

添加一个按钮和CommonDialog控件 如下图CommonDialog添加方法自行百度
工程引用如下图
Excel14.0 library 由安装的office版本决定
源代码:

Private Sub Command1_Click()
     
     Dim sourceFilePath As String
     Me.CommonDialog1.Filter = "Excel (*.xls;*.xlsx)|*.xls;*.xlsx|" '过滤文件
     Me.CommonDialog1.FilterIndex = 2
     Me.CommonDialog1.ShowOpen
     If Me.CommonDialog1.FileName <> "" Then
        sourceFilePath = Me.CommonDialog1.FileName  '获取文件路径
        MsgBox sourceFilePath
     Else
        MsgBox "未选择文件"
        Exit Sub
     End If
     
     Dim rs As ADODB.Recordset
     Set rs = GetExcelRs(sourceFilePath, "sheet1") '调用方法
     MsgBox rs.Fields(0)
End Sub

'连接Excel方法**

Function GetExcelRs(ByVal sFile As String, Optional ExcelSheetName As String = "sheet1", Optional ErrInfo As String) As ADODB.Recordset

   On Error GoTo Err
   Dim rs As ADODB.Recordset
   Set rs = New ADODB.Recordset
   Dim ConnStr As String
   Dim sql As String

   ConnStr = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source = " & sFile & ";Extended Properties ='Excel 12.0;HDR=YES;IMEX=1'"  '调用oledb连接,并将Excel表格中的首行做为标题行

   rs.Open "SELECT * FROM [" & ExcelSheetName & "$]", ConnStr, 1, 3
   Set GetExcelRs = rs
   Set rs = Nothing
   Exit Function
Err:
   ErrInfo = Err.Description
   MsgBox ErrInfo
End Function

注意:rs.open语句里的$符号缺失会报"Microsoft Access数据库引擎找不到对象sheet1…"
在这里插入图片描述

  • 2
    点赞
  • 19
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值