|
楼主 |
发表于 2018-7-23 20:47
|
显示全部楼层
代码如下
Public Function JOINFI(arr As Variant, delimiter As String, Optional quotes As String = "") As String '定义函数JOINFI
Dim i As Integer, el
For Each el In arr
i = 1 + i
If i = 1 Then
JOINFI = quotes & el & quotes
Else
JOINFI = JOINFI & delimiter & quotes & el & quotes
End If
Next el
End Function
Public Sub Import()
Dim rngCur As Range, Cell As Range, i As Integer
Dim sInsert As String, iRowscount As Integer
Dim Con As ADODB.Connection
With Worksheets("import")
Set rngCur = .Range(.Range("a2"), .Range("a2").End(xlDown))
'获取数据区域
End With
For Each Cell In rngCur
i = 1 + i
If i = 1 Then
sInsert = "(" + JOINFI(Cell.Offset(0, 1).Resize(1, 6).Value, ",", """") + ")"
Else
sInsert = sInsert + "," + "(" + JOINFI(Cell.Offset(0, 1).Resize(1, 6).Value, ",", """") + ")"
End If
Next Cell
'用for each 把数据添加到SQL命令字符串sInsert
sInsert = "insert `student`(`chname`,`enname`,`sex`,`age`,`country`,`comments`) value" + sInsert
'构造插入记录的SQL命令字符串sInsert
Set Con = New ADODB.Connection
Con.Open "Driver={MySQL ODBC 5.3 Unicode Driver};Server=127.0.0.1;Port=3306;Database=wxh;Uid=root;Pwd=haosql;OPTION=3;Stmt=Set Names 'GBK';"
Con.Execute sInsert, iRowscount, adCmdText
Con.Close: Set Con = Nothing
MsgBox "导入 " & iRowscount & " 行", vbOKOnly, ""
End Sub
还是新手 论坛搜索了 还是不太懂 再哪加个判断重复值 |
|