我试图通过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
有人可以帮助我吗?
答案 0 :(得分:1)
这可以用于输入:
带来这个:
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)