我有一个模板,用户输入帐户信息,信息的默认范围是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工作正常,做我需要做的事情,但我遇到的问题是我无法触发workheet_Change。
提前致谢
那里
我使用你的代码运行了一点测试,我注意到的第一件事是,你设置了Application.EnableEvents to False
并且你没有重新设置它,所以你取消任何事件,如Worksheet_Change Event
一旦修复事件将触发任何时候单元格B18更改,除非输入的值来自粘贴(不确定原因),但如果使用相交方法,则即使值来自复制粘贴,它也会起作用。
我对你的代码进行了一些小的调整,我认为它现在有效。请仔细检查并尝试一下。
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