excelperfect 标签:VBA,Worksheet_Change事件 我们可以在工作表中保存所有输入的值,而不受工作簿是否关闭的影响。 情形1:保留所有输入数字中的最小值和最大值 在单元格A2输入数字,单元格B2中会保存所有输入数字中的最小值,单元格C2中会保存所有输入数字中的最大值,如下图1所示。 图1 代码如下: Private Sub Worksheet_Change(ByVal Target As Range) With Target If .Address <> '$A$2' Then Exit Sub If Len(.Value) = 0 Then Exit Sub If .Value <Range('B2').Value Then Range('B2').Value =.Value End If If .Value >Range('C2').Value Then Range('C2').Value =.Value End If End With End Sub Worksheet_Change事件监视工作表中的单元格或单元格区域,并在满足条件时执行操作。 上面的代码执行各种检查。如果当前单元格不是单元格A2,则退出程序。如果单元格A2中的内容长度为零,则退出程序。如果代码仍在运行,则表示当前单元格为A2,且单元格A2中的内容长度不为零。 代码: If .Value < Range('B2').Value Then Range('B2').Value =.Value 如果单元格A2中的值小于单元格B2中的值,则将A2中的值放入单元格B2,这将保留所有输入值的最小值。对于最大值也是如此。 情形2:保留单元格中输入的所有值 将指定单元格中输入的值保留在工作表中,如下图2所示。 图2 代码如下: Private Sub Worksheet_Change(ByVal Target As Range) Dim nextrow As Integer Dim Savetxt As Range Set Savetext = Range('C1:C100') nextrow =Application.WorksheetFunction.CountA(Savetext) With Target If .Address <> '$A$1' Then Exit Sub If Len(.Value) = 0 Then Exit Sub Range('C' & nextrow +1).Value = .Value Range('A1').ClearContents End With End Sub 情形3:将指定单元格区域中输入的值保存 在A1:D5范围内输入单词,这些单词将存储在F列中。 图3 代码如下: Private Sub Worksheet_Change(ByVal Target As Range) Dim nextrow As Integer Dim Savetxt As Range Set Savetxt = Range('A1:D5') nextrow =Application.WorksheetFunction.CountA(Savetxt) With Target On Error GoTo Handler If Target.Column > 4 Then Exit Sub If Target.Row > 5 Then Exit Sub If Len(.Value) = 0 Then Exit Sub Range('F' & nextrow +1).Value = .Value End With Handler: End Sub |
|
来自: hercules028 > 《VBA》