2017-09-04 294 views
1

我试图通过VBA的方式将数据从Excel插入到SQL数据库中。我使用Excel中的结构如下:使用两个do循环向数据库中正确插入数据

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 

有人可以帮我吗?

+0

'5's从哪里来? – Tom

+0

该脚本使用字符串,即“选项#1”和“选项#2”来查找相应的optionvalue id,选项#1为2,#option2为5 – user2237168

+0

我可能会丢失一些东西,但不能看看你的源数据是如何得到的 – Tom

回答

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

+0

谢谢你的Vityata你的答案。但是,这不完全是我想要的。我编辑了我的主要问题。也基于汤姆的评论。希望这个问题现在更有意义,希望你仍然愿意帮助我 – user2237168

+0

@ user2237168 - 如果你可以使它成为一个最小的工作示例(最小工作示例stackoverflow),我会尝试。例如,尝试删除问题中所有无用的部分,并尽量只留下输入或输出,只要它可以轻松复制即可。例如,在我的答案中没有连接字符串或复杂的SQL查询。 – Vityata

+0

亲爱的Vityata。我现在编辑了我的主要问题,只包含必要的代码和输出。对不起,我首先不清楚。我希望现在我的主要问题更有意义。 – user2237168

1

我可能失去了一些东西,但似乎变量visible是stucked有3排.Cells(3, p),这就是为什么它只是将方案1,不顾第一个循环。

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

编辑来改变它:你说的是它不工作,但似乎当我测试了它,我得到正确的结果。

SQL字符串被执行是这里的问题时,有可能。

enter image description here

+0

谢谢库拉波。我已经尝试过,但没有奏效。 – user2237168

+0

再次感谢您的帮助Kulapo。对此,我真的非常感激!我最终使用了Vityata的解决方案。 – user2237168

+0

但你确实是对的。这很奇怪,SQL不起作用。我观察到,在添加K(如Vityata的解决方案中)时,SQL确实有效并且数据正确插入... – user2237168

相关问题