【问题标题】:Excel VBA: Repeat IF statement on string range to retrospective rowsExcel VBA:在字符串范围上重复 IF 语句到追溯行
【发布时间】:2017-01-05 16:20:10
【问题描述】:

我正在努力寻找我需要的答案,希望有人能提供帮助。我觉得我编写的代码需要以不同的方式来实现我想要实现的目标。

我已经生成了一些代码,这些代码在一个单元格上生成一个 IF 语句,并在旁边的另一个单元格中显示相应的描述,我还添加了代码以确保它在此值更改时自动更新。这行得通。

我现在需要扩展代码,以便循环单元格并重复相同的功能。检查 IF 语句并在其旁边的相应单元格中显示相应的描述。

工作表 VBA:

Private Sub Worksheet_Change(ByVal Target As Range)
  If Intersect(Target, Me.Range("A2:A10")) Is Nothing Then Exit Sub
  Application.EnableEvents = False
  On Error GoTo Finalise
  Call Material_String
  Finalize:
  Application.EnableEvents = True
End Sub

模块:

Sub Material_String()
  Dim MaterialOption As String
  Dim MaterialDetail As String
  MaterialOption = Range("A2").Value
  If MaterialOption = "a" Then MaterialDetail = "a is bloody good"
  If MaterialOption = "b" Then MaterialDetail = "b is excellent"
  If MaterialOption = "c" Then MaterialDetail = "c is most good"
  If MaterialOption = "d" Then MaterialDetail = "d is simply the best"
  If MaterialOption = "e" Then MaterialDetail = "e's are just amazing"
  Range("C2").Value = MaterialDetail
End Sub

任何指针将不胜感激。

【问题讨论】:

  • 查看how to loop through a range。此外,Select Case 也可能会有所帮助,而不是 If 声明。
  • 如果你的代码是通过改变一个单元格来激活的,如果它的大部分单元格都没有改变,为什么你需要它循环整个范围呢?我原以为你是正确的。

标签: excel loops if-statement row vba


【解决方案1】:

您可能不想遍历所有行。您可能只想处理已更改的单元格。

您可以通过更改您的“工作”子例程(即Material_String)来接受一个单元格作为参数,并更改您的Worksheet_Change 事件以传递已更改的单元格。

工作表 VBA:

Private Sub Worksheet_Change(ByVal Target As Range)
  If Intersect(Target, Me.Range("A2:A10")) Is Nothing Then Exit Sub
  Application.EnableEvents = False
  On Error GoTo Finalise
  Dim c As Range
  'Loop through each changed cell, just in case there is more than one
  For Each c In Intersect(Target, Me.Range("A2:A10")).Cells
      Call Material_String(c)
  Next
  Finalize:
  Application.EnableEvents = True
End Sub

模块:

Sub Material_String(c As Range)
  Dim MaterialOption As String
  Dim MaterialDetail As String
  MaterialOption = c.Value
  If MaterialOption = "a" Then MaterialDetail = "a is bloody good"
  If MaterialOption = "b" Then MaterialDetail = "b is excellent"
  If MaterialOption = "c" Then MaterialDetail = "c is most good"
  If MaterialOption = "d" Then MaterialDetail = "d is simply the best"
  If MaterialOption = "e" Then MaterialDetail = "e's are just amazing"
  c.Offset(0, 2).Value = MaterialDetail
End Sub

【讨论】:

  • 谢谢YowE3K。 c 是否意味着它正在查看单元格?大概(我似乎发现)我不能在另一个 IF Intersect 语句上再次引用 C 来查看另一列并在同一张表上调用不同的模块子?
  • @MattCass 变量c 没有什么特别之处。它被定义为 Range 对象(即对范围的引用),我在 Change 事件中使用它来单独引用 A 列(第 2 行和第 10 行之间)中更改的每个单元格。没有理由不能在 Change 事件代码中包含另一个循环,例如 For Each c In Intersect(Target, Me.Range("D:D")).Cells Call Another_Sub(c) Next
  • 请更正单词 Finalize 中的拼写错误。因为两个标签需要具有相同的拼写。我无法进行此更改,因为不允许编辑少于指定的字符。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-08-15
  • 1970-01-01
  • 2014-01-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多