我有一个工作表,该工作表使用Ado连接到SQL DB,并将数据库的内容上载到excel工作表中。我的那部分工作得很好。现在,我想检查一下插入数据后单元格是否发生了变化。这是到目前为止我在Worksheeet_Change中的代码。
Private Sub Worksheet_Change(ByVal Target As range)
Dim KeyCells As range
Set KeyCells = range("Table:Environment")
If Not Application.Intersect(KeyCells, range(Target.Address)) _
Is Nothing Then
range("CleanHeaders").ClearContents
range("CleanDates").ClearContents
Call SQL_Connect.connect
Call Data_Download.header_download
Call Data_Download.download_data
Call SQL_Connect.close_connection
End If
Dim DataRng As range, roww As Long
Dim rng As range
Set DataRng = Intersect(range("DataStart:Z10000"), Target)
If Not DataRng Is Nothing Then
For Each rng In DataRng
roww = rng.Row
If Not rng.Value = " " Then
Cells(roww, "AA").Value = "1"
Else
Cells(roww, "AA").Value = "0"
End If
Next
End If
On Error GoTo 0
End Sub
为了快速入门,这是代码中的内容。第一部分着重介绍工作表中的特定框。更改后,它将调用连接,下载标题和数据,然后关闭连接。就像我说的那样,此部分运行正常,我对此没有任何疑问。下一部分是我尝试检查这些单元格中的更改。问题是,每次我清理表或将新数据上传到表时,它都认为这是一个更改,并将所有行都放入1。 我想在将数据下载到工作表之后检测这些更改。我将如何解决此问题以正确实现这一目标?预先感谢!
答案 0 :(得分:1)
任何发生变化的事件都有可能被激活。为防止这种情况发生,请在使用EnableEvents
运行子程序时禁用事件Private Sub Worksheet_Change(ByVal Target As range)
Application.EnableEvents = False
Dim KeyCells As range
Set KeyCells = range("Table:Environment")
If Not Application.Intersect(KeyCells, range(Target.Address)) _
Is Nothing Then
range("CleanHeaders").ClearContents
range("CleanDates").ClearContents
Call SQL_Connect.connect
Call Data_Download.header_download
Call Data_Download.download_data
Call SQL_Connect.close_connection
End If
Dim DataRng As range, roww As Long
Dim rng As range
Set DataRng = Intersect(range("DataStart:Z10000"), Target)
If Not DataRng Is Nothing Then
For Each rng In DataRng
roww = rng.Row
If Not rng.Value = " " Then
Cells(roww, "AA").Value = "1"
Else
Cells(roww, "AA").Value = "0"
End If
Next
End If
On Error GoTo 0
Application.EnableEvents = True
End Sub