环境说明:excel 2010 mysql5.6
Private Sub worksheet_change(ByVal target As Range)
carD = Cells(Selection.Row, 9)
If Selection.Column = 9 Or Len(Trim(carD)) >= 7 Then
Call updateQk(target)
End If
End Sub
Function updateQk(target)
Application.EnableEvents = False
If Selection.Address Like "*,*" Then
p = Split(Selection.Address, ",")
For I = LBound(p) To UBound(p)
q = Split(p(I), "$")
If UBound(q) >= 2 Then
carNo = Cells(q(2), 9)
steelNo = Cells(q(2), 2)
carNo = Mid(UCase(Trim(carNo)), 1, 7)
If Len(Trim(steelNo)) >= 1 And Len(Trim(carNo)) >= 7 Then
Rem MsgBox steelNo & carNo
Call updateData(carNo, steelNo)
End If
End If
Next
ElseIf Selection.Address Like "*:*" Then
p = Split(Selection.Address, "$")
If UBound(p) >= 4 Then
For I = Replace(p(2), ":", "") To Replace(p(4), ":", "")
carNo = Cells(I, 9)
steelNo = Cells(I, 2)
carNo = Mid(UCase(Trim(carNo)), 1, 7)
If Len(Trim(steelNo)) >= 1 And Len(Trim(carNo)) >= 7 Then
Rem MsgBox steelNo & carNo
Call updateData(carNo, steelNo)
End If
Next
ElseIf UBound(p) >= 2 Then
For I = Replace(p(1), ":", "") To Replace(p(2), ":", "")
carNo = Cells(I, 9)
steelNo = Cells(I, 2)
carNo = Mid(UCase(Trim(carNo)), 1, 7)
If Len(Trim(steelNo)) >= 1 And Len(Trim(carNo)) >= 7 Then
Rem MsgBox steelNo & carNo
Call updateData(carNo, steelNo)
End If
Next
Else
rowId = CInt(target.Row)
carNo = Cells(rowId, 9)
steelNo = Cells(rowId, 2)
carNo = Mid(UCase(Trim(carNo)), 1, 7)
If Len(Trim(steelNo)) >= 1 And Len(Trim(carNo)) >= 7 Then
Rem MsgBox steelNo & carNo
Call updateData(carNo, steelNo)
End If
End If
Else
rowId = CInt(target.Row)
carNo = Cells(rowId, 9)
steelNo = Cells(rowId, 2)
carNo = Mid(UCase(Trim(carNo)), 1, 7)
If Len(Trim(steelNo)) >= 1 And Len(Trim(carNo)) >= 7 Then
Rem MsgBox steelNo & carNo
Call updateData(carNo, steelNo)
End If
End If
Application.EnableEvents = True
End Function
Function updateData(carNo, steelNo)
Rem 获取数据库连接
Dim conn As ADODB.Connection
Set conn = New ADODB.Connection
conn.ConnectionString = "Driver={MySQL ODBC 5.3 Unicode Driver};Server=127.0.0.1;Port=3306;Database=t;Uid=root;Pwd=1234;OPTION=3;"
conn.Open
carNo = Mid(UCase(Trim(carNo)), 1, 7)
If Len(Trim(steelNo)) >= 1 And Len(Trim(carNo)) >= 7 Then
Sql = "UPDATE table1 SET carNo= '" & carNo & "' WHERE id='" & steelNo & "'"
Rem 执行更新
conn.Execute (Sql)
End If
Rem 关闭连接
conn.Close: Set conn = Nothing
End Function