ExcelHome技术论坛

 找回密码
 免费注册

QQ登录

只需一步,快速开始

快捷登录

搜索
EH技术汇-专业的职场技能充电站 妙哉!函数段子手趣味讲函数 Excel服务器-会Excel,做管理系统 效率神器,一键搞定繁琐工作
HR薪酬管理数字化实战 Excel 2021函数公式学习大典 Excel数据透视表实战秘技 打造核心竞争力的职场宝典
让更多数据处理,一键完成 数据工作者的案头书 免费直播课集锦 ExcelHome出品 - VBA代码宝免费下载
用ChatGPT与VBA一键搞定Excel WPS表格从入门到精通 Excel VBA经典代码实践指南
查看: 1206|回复: 1

[求助] 希望用VBA将Excel数据表格直接导入SQL Server数据库2005

[复制链接]

TA的精华主题

TA的得分主题

发表于 2017-6-12 18:39 | 显示全部楼层 |阅读模式
[广告] Excel易用宝 - 提升Excel的操作效率 · Excel / WPS表格插件       ★免费下载 ★       ★ 使用帮助
希望用VBA将Excel数据表格直接导入SQL Server数据库2005。原始表请见附件

代码如下:
Option Explicit

Public Sub CreateAllSheetsInsertScript()
On Error GoTo ErrorHandler 'recordset and connection variables
Dim Row As Long
Dim Col As Integer
'To store all the columns available in the all of the worksheets
Dim ColNames(100) As String
Dim ColCount As Integer
Dim MaxRow As Long
Dim CellColCount As Integer
Dim StringStore As String 'Temporary variable to store partial statement
Dim InsertScriptHead As String
Dim DBname As String
Dim TableName As String
Dim Ret As Long
Dim Cnxn As New ADODB.Connection //可是在这里显示“用户定义类型未定义”
DBname = "DB1"
TableName = "Table1"
Cnxn.Open "Provider=SQLOLEDB;Data Source=localhost;Initial Catalog=" & DBname & ";Integrated Security=SSPI;"
Application.ScreenUpdating = False
Dim sh As Worksheet
For Each sh In ActiveWorkbook.Sheets
    With sh
        .Select
        Col = 1
        Row = 1
        ColCount = 0
         'Get Columns from the sheet
        Do Until .Cells(Row, Col) = "" 'Loop until you find a blank.
            ColNames(ColCount) = "[" & .Cells(Row, Col) & "]"
            ColCount = ColCount + 1
            Col = Col + 1
        Loop
        ColCount = ColCount - 1
        'Inputs for the starting and ending point for the rows
        Row = 2
        MaxRow = .[A1].End(xlDown).Row
        CellColCount = 0
        '.Name will give the current active sheet name
        'this can be treated as table name in the database
        InsertScriptHead = "INSERT INTO [dbo].[" & TableName & "] ( "
        Do While CellColCount <= ColCount
            InsertScriptHead = InsertScriptHead & ColNames(CellColCount)
             'To avoid "," after last column
            If CellColCount <> ColCount Then
                InsertScriptHead = InsertScriptHead & " , "
            End If
            CellColCount = CellColCount + 1
        Loop
        InsertScriptHead = InsertScriptHead & " ) VALUES ( "
        Do While Row <= MaxRow
            'Here it will print "insert into [TableName] ( [Col1] , [Col2] , ..."
            'For printing the values for the above columns
            StringStore = InsertScriptHead
            CellColCount = 0
            Do While CellColCount <= ColCount
                StringStore = StringStore & IIf(Len(Trim(.Cells(Row, CellColCount + 1).Value)) = 0, "NULL", " '" & Replace(CStr(.Cells(Row, CellColCount + 1)), "'", "''") & "'")
                If CellColCount <> ColCount Then
                    StringStore = StringStore & ", "
                End If
                CellColCount = CellColCount + 1
            Loop
            'Here it will print "values( 'value1', 'value2', ..."
            Cnxn.Execute StringStore & ")"
            Row = Row + 1
        Loop
    End With
Next sh
Application.ScreenUpdating = True
' clean up
Cnxn.Close
Set Cnxn = Nothing
MsgBox ("Successfully Done")
Exit Sub

ErrorHandler:
   ' clean up
    If Not Cnxn Is Nothing Then
        If Cnxn.State = adStateOpen Then Cnxn.Close
    End If
    Set Cnxn = Nothing

    If Err <> 0 Then
        MsgBox Err.Source & "-->" & Err.Description, , "Error"
    End If
End Sub

元件价格.rar

7.7 KB, 下载次数: 9

TA的精华主题

TA的得分主题

发表于 2018-7-26 09:17 | 显示全部楼层
[广告] VBA代码宝 - VBA编程加强工具 · VBA代码随查随用  · 内置多项VBA编程加强工具       ★ 免费下载 ★      ★使用手册
我是用ADDNEW增加的
            Rsx.AddNew
            For J = 1 To Rsx.Fields.Count
                If J = 1 Then
                Rsx.Fields(Cells(1, J).Value) = Autod
                Autod = Autod + 1
                Else
                Rsx.Fields(Cells(1, J).Value) = Sf.Cells(I, J).Value
                End If
            Next J
            Rsx.Update
            Next I
您需要登录后才可以回帖 登录 | 免费注册

本版积分规则

手机版|关于我们|联系我们|ExcelHome

GMT+8, 2024-9-28 11:18 , Processed in 0.032875 second(s), 11 queries , Gzip On, MemCache On.

Powered by Discuz! X3.4

© 1999-2023 Wooffice Inc.

沪公网安备 31011702000001号 沪ICP备11019229号-2

本论坛言论纯属发表者个人意见,任何违反国家相关法律的言论,本站将协助国家相关部门追究发言者责任!     本站特聘法律顾问:李志群律师

快速回复 返回顶部 返回列表