zoukankan      html  css  js  c++  java
  • Excel中VBA 连接 数据库 方法- 摘自网络

    Sub GetData()     
         Dim strConn As String, strSQL As String 
         Dim conn As ADODB.Connection 
         Dim ds As ADODB.Recordset 
         Dim col As Integer 
         
        '清空电子表格的所有数据      
        Cells.Clear 
         
        '连接数据库的字符串      
        strConn = "Provider=SQLOLEDB.1;Persist Security Info=True;User ID=name;Password=pwd;Initial Catalog=dataname;Data Source=servername" 
        '查询语句 
         strSQL = "select * from table1" 
         Set conn = New ADODB.Connection 
         Set ds = New ADODB.Recordset 
        '打开数据库连接 
         conn.Open strConn 
         
         With ds 
       '根据查询语句获得数据 
             .Open strSQL, conn 
             
             '自动控制加入所有列标题 
             For col = 0 To ds.Fields.Count - 1 
        '请注意Offset(0, col)中的参数一定要正确噢 
                 Range("A1").Offset(0, col).Value = ds.Fields(col).Name 
             Next 
             
            '加入所有行数据 
             Range("a1").Offset(1, 0).CopyFromRecordset ds 
         End With 
         
        '以下是关闭数据库连接和清空资源 
         Set ds = Nothing 
         conn.Close 
         Set conn = Nothing 
    End Sub 

     

    注意:

    1. 保存时您可能看到以下消息:“Privacy warning:This document contains macros, ActiveX Controls, XML expansion pack...

    解决方法:

    要取消该警告,回到当前Excel-> Options -> Trust Center -> Trust Center Settings...-> Privacy Options取消选中Remove Personal information from file properties on save”复选框。

    2. 保存时您可能看到以下消息:“

    the following features cannot be saved in macro-free workbooks 
    vb project 
    to save a file with these features click no  and then choose a macro-enabled file type in the file type list.
    to continue saving as a macro-free workbook, click yes"

    解决方法:

    1. 你所打开的文件是只读的
    2. 你所打开的文件是未启用宏的工作薄xlsx,而你使用了宏,所以提示需要你保存为xlsm

  • 相关阅读:
    android自己定义控件系列教程----视图
    Android怎样监听蓝牙耳机的按键事件
    Putty SSH简单使用
    Linux配置无线网卡驱动实现无线上网
    Oracle在中文环境下出现乱码解决办法
    百度云盘破解限速|个人值得拥有
    Ubuntu安装出现左上角光标一直闪解决方式
    ubuntu-16.4TLS安装QQ
    2015毕业找工作纪实|一年的蜕变毕业生
    安装rpm包时遇到Header V3 DSA signature: NOKEY时解决办法
  • 原文地址:https://www.cnblogs.com/haoliansheng/p/3274180.html
Copyright © 2011-2022 走看看