【发布时间】:2020-04-08 09:20:57
【问题描述】:
我正在尝试构建一个工作表,让我和我的同事可以在工作表中填写变量,就像在与客户进行对话时所做的那样。到目前为止我已经成功了,但是宏变得非常非常慢......我已经禁用了 ScreenUpdating、DisplayPageBreaks、Calculation 和 Events。
实际上,我很确定这需要很长时间,因为Private Sub Worksheet_Change 很广泛。当单元格仍然为空时,我使用一些初始格式,以便我的同事知道在单元格中放入什么。但是这个过程会单独重复大约 170 行。它看起来像这样:
Private Sub Worksheet_Change(ByVal Target As Range)
If Cells(19,3).Value="" Then Cells(19,3).Value="Fill in x.."
Cells(19,3).Font.Fontstyle = "Italic"
Cells(19,3).Font.ColorIndex = 16
If Cells(20,3).Value="" Then Cells(20,3).Value="Fill in y.."
Cells(20,3).Font.Fontstyle = "Italic"
Cells(20,3).Font.ColorIndex = 16
If Cells(25,2).Value="" Then Cells(25,2).Value="Fill in z.."
Cells(25,2).Font.Fontstyle = "Italic"
Cells(25,2).Font.ColorIndex = 16
If Cells(70,3) = True Then Cells(70,3).Value = "Comment.."
If Cells(70,3) = False Then Cells(70,3).Value = ""
Cells(70,3).Font.Fontstyle = "Italic"
Cells(70,3).Font.ColorIndex = 16
这适用于许多其他细胞。我想探索当时是否可以只运行Private Sub Worksheet_Change 的一部分。例如,它只检查一个单元格是否在该人当前工作的章节中发生变化。有人可以帮我解决这个问题,或者让我朝着正确的方向前进吗?
提前致谢!
【问题讨论】:
-
如何识别“当前工作的人所在的章节”?如果是更改的单元格,则仅针对
TargetRange 运行代码 -
可以对每个block进行wrap并检查cell是否被改变,
If Not Intersect(Target, Cells(19,3)) Is Nothing Then. -
此外,如果
If - Then语句在您的所有情况下都在一行中完成,那么它旁边的代码将运行,而不管它们上面的 if 结果如何。因此,在您的情况下,所有语句都将运行(包括 If 条件和其他),从而使 if 语句变得多余。因此,即使Cells(19,3).Value<>""它仍然会检查条件并生成 Cells(19,3).Font italic 和 colorindex 16。更好地使用 if 块,在下一行执行操作并使用 end ifs。
标签: excel vba formatting