使用两个do循环将数据正确插入数据库

时间:2017-09-04 11:03:31

标签: sql sql-server excel vba excel-vba

我试图通过VBA将数据从Excel插入到SQL数据库中。我在Excel中使用以下结构:

enter image description here

我使用以下代码:

 Private Sub CommandButton1_Click()

 Dim i                 As Integer
 Dim p                 As Integer
 Dim product           As String
 Dim version           As String
 Dim opt               As String
 Dim visible           As String
 Excel.Worksheets("Blad2").Select

i = 3
Do Until IsEmpty(Cells(i, 1))

opt = ActiveSheet.Cells(i, 1)

    p = 3
    Do Until IsEmpty(Cells(1, p))

        product = ActiveSheet.Cells(1, p)
        version = ActiveSheet.Cells(2, p)
        visible = ActiveSheet.Cells(i, p)

        Debug.Print product & version & opt & visible

    p = p + 1
    Loop

i = i + 1
Loop

End Sub

运行脚本的结果如下:

  product#1  version#1   option#1   0
  product#1  version#2   option#1   1
  option#1

虽然我希望它导致:

  product#1  version#1   option#1   0
  product#1  version#2   option#1   1
  product#1  version#1   option#2   0
  product#1  version#2   option#2   0

有人可以帮助我吗?

2 个答案:

答案 0 :(得分:1)

这可以用于输入:

enter image description here

带来这个:

product1 version1 option1 0
product1 version2 option1 1
product1 version1 option2 0
product1 version2 option2 0
Option Explicit

Public Sub TestMe()

    Dim k           As Long
    Dim i           As Long
    Dim p           As Long
    Dim product     As String
    Dim version     As String
    Dim opt         As String
    Dim visible     As String

    With ActiveSheet
        i = 3
        Do Until IsEmpty(.Cells(i, 1))
        p = 3
        k = 0
            Do Until IsEmpty(.Cells(1, p))
                opt = .Cells(i, 1)
                product = .Cells(1, p)
                visible = .Cells(i, p)
                version = .Cells(2, 3 + k)
                k = k + 1

                Debug.Print product & " " & version & " " & opt & " " & visible
                p = p + 1
            Loop
            i = i + 1
        Loop
    End With
End Sub

通常,请考虑为变量and using Long instead of Integer使用更好的名称。

答案 1 :(得分:1)

我可能会遗漏一些东西,但似乎变量visible被第3行.Cells(3, p)所困,这就是为什么它只插入选项1并忽略第一个循环。

尝试使用visible = ActiveSheet.Cells(i, p)

进行更改

编辑:你说它不起作用,但是当我测试它时,我得到了正确的结果。

有可能在此处执行SQL字符串时出现问题。

enter image description here