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

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

在这里输入图像说明

我正在使用下面的代码:

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 

有人能帮我吗?

这是应该为这个input工作的东西:

在这里输入图像说明

带来这个:

 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 

通常,考虑为variables使用更好的名称, 并使用Long而不是Integer

我可能会丢失一些东西,但似乎variablesvisible与第3行.Cells(3, p) ,这就是为什么它只插入选项1,忽略第一个循环。

尝试改变它与visible = ActiveSheet.Cells(i, p)

编辑:你说这是行不通的,但似乎当我testing它,我得到正确的结果。

有可能在这里执行SQLstring是个问题。

在这里输入图像说明