输入单元格值时的格式范围



>我有一个模板,用户在其中输入帐户信息,信息的默认范围是范围 B18 到 S52。这非常适合屏幕,并且对于90%的时间输入细节来说是一个足够大的范围。但是,在某些情况下,使用的数据可能只有几百行。它通常复制并粘贴,但会使工作表看起来很混乱,因为它超出了默认范围。

我正在尝试使格式动态化,如果用户输入的数据超出默认范围,则会触发一个宏,该宏将计算行数并重新格式化范围。

到目前为止,我还没有在网上研究的代码是:

Private Sub Worksheet_Change(ByVal Target As Range)
    If Target.Address = "$B$18" Then
        Call CountLoc
    End If
End Sub
Public Sub CountLoc()
With Application
    .DisplayAlerts = False
    '.Calculation = xlManual
    .EnableEvents = False
    .ScreenUpdating = False
End With
Dim LocCount As Long
Dim WsInput As Worksheet
Dim i As Long
Dim rng As Range
Set WsInput = Sheets("Account Input")
With WsInput
    LocCount = .Range("B1048576").End(xlUp).row - 17
End With
If LocCount > 35 Then
Set rng = WsInput.Range(WsInput.Cells(18, 2), WsInput.Cells(17 + LocCount, 19))
With rng
    .Interior.Color = RGB(220, 230, 241)
    .Borders.LineStyle = xlContinuous
    .Borders.Color = vbBlack
    .Borders.Weight = xlThin
End With
For i = 1 To LocCount Step 2
Rows(18 + i).EntireRow.Interior.Color = vbWhite
Next i
Else
Exit Sub
End If

这基本上每隔一行将浅蓝色和白色着色,并为每个单元格添加边框。Count Loc 工作正常并执行我需要它执行的操作,但我遇到的问题是我无法触发worksheet_Change。

提前致谢

那里

使用您的代码进行了一个小测试,我注意到的第一件事是您设置了Application.EnableEvents to False并且没有将其重新设置,因此您将取消任何事件,例如Worksheet_Change Event一旦修复,该事件将在单元格 B18 更改时随时触发,除非输入的值来自粘贴(不确定为什么(,但如果您使用 Intersect 方法,那么它可以工作即使该值来自复制粘贴。

我对你的代码做了一些小的调整,我认为它现在可以工作了。 请查看并尝试一下。

Private Sub Worksheet_Change(ByVal Target As Range)
If Not Intersect(Target, ThisWorkbook.Sheets("Account Input").Range("B18")) Is Nothing Then
   Call CountLoc
End If
End Sub
Public Sub CountLoc()
Dim LocCount As Long
Dim WsInput As Worksheet
Dim i As Long
Dim rng As Range
Set WsInput = Sheets("Account Input")
With WsInput
 LocCount = .Cells(.Rows.Count, "B").End(xlUp).Row
End With
If LocCount > 35 Then
Set rng = WsInput.Range(WsInput.Cells(18, 2), WsInput.Cells(LocCount, 19))
With rng
    .Interior.Color = RGB(220, 230, 241)
    .Borders.LineStyle = xlContinuous
    .Borders.Color = vbBlack
    .Borders.Weight = xlThin
End With
For i = 18 To LocCount Step 2
Set rng = WsInput.Range(WsInput.Cells(i, 2), WsInput.Cells(i, 19))
rng.Interior.Color = vbWhite
Next i
Else
Exit Sub
End If
End Sub

最新更新