.Cells VBA参考问题

时间:2011-12-01 22:59:25

标签: mysql excel vba odbc

我在下面有这个VBA,用于遍历每个WS并插入每个数据集的前4行。

这在with中很好用,但这只能让我指定一张表,而不是全部通过它们。我把它带出来并得到了#34;无效或不合格的参考"。在此之后我添加了ActiveSheet。进入'细胞'方法。

现在我收到以下错误:

" ODBC驱动程序不支持所请求的属性"

我如何才能获得.Cells资格?还是有替代方案吗?我正在使用excel 2010和mysql。

Public Function InsertData()

Dim rs As ADODB.Recordset
Dim oConn As ADODB.Connection
Dim WS As Worksheet
Dim strsql As String

Set rs = New ADODB.Recordset
  Set oConn = New ADODB.Connection
oConn.Open "DRIVER={MySQL ODBC 5.1 Driver};" & _
    "SERVER=server.host.com;" & _
    "DATABASE=datatime;" & _
    "USER=boulders;" & _
    "PASSWORD=rocks;" & _
    "Option=3"


For Each WS In ActiveWorkbook.Worksheets

    For rowcursor = 4 To 8
        strsql = "INSERT INTO workflow_metrics (id, code) " & _
            "VALUES (" & (ActiveSheet.Cells(rowcursor, 1)) & "," & _
            "'" & (ActiveSheet.Cells(rowcursor, 2)) & "')"

       rs.Open strsql, oConn, adOpenDynamic, adLockOptimistic

    Next
Next WS


End Function

2 个答案:

答案 0 :(得分:5)

我想你想要:

Param1.Value = WS.Cells(rowcursor, 1)

答案 1 :(得分:1)

  

我如何才能获得.Cells资格?还是有替代方案吗?

这不是问题。问题是您尝试使用数据修改查询(rs.open)打开记录集(INSERT)。

对于DML,您想使用ADODB.Command.Execute

此外,如果您无法控制电子表格中的值,那么您将打开SQL注入攻击。您应该使用参数化查询。

 Dim Cmd As ADODB.Command
 Set Cmd = New ADODB.Command
 Cmd.ActiveConnection = oConn
 Cmd.CommandText = "INSERT INTO workflow_metrics (id, code) VALUES (?,?)"

 Set Param1 = Cmd.CreateParameter(, adInteger, adParamInput, 5)
 Set Param2 = Cmd.CreateParameter(, adInteger, adParamInput, 5)


 For Each WS In ActiveWorkbook.Worksheets


     For rowcursor = 4 To 8
         Param1.Value = WS.Cells(rowcursor, 1) 'As Doug Glancy this should be WS not ActiveSheet'
         Param2.Value = WS.Cells(rowcursor, 2)
         cmd1.Execute
     Next
 Next  WS