【问题标题】:Variable text depending on other cells value可变文本取决于其他单元格值
【发布时间】:2020-07-05 02:59:23
【问题描述】:

我希望某个单元格根据其他单元格的值显示不同的值。例如,在我的工作表中,A1 是“电影标题”,A2 是“持续时间”,A3 是“类型”。 A4 应显示消息“您应该介绍...”和为空的单元格。例如,如果我只完成了 A2,A4 应该显示“你应该介绍电影的标题和类型”。

我之前使用 Worksheet_Change 对宏进行了编程,以便工作表根据其他值进行更改。

到目前为止,我已经开发了这段代码:

Sub Macro1()

If Range("A1") = "Introduce text" And _
Range("A2") <> "Introduce text" And _
Range("A3") <> "Introduce text" Then

Range("A4") = "You should introduce Title of the film"

Else

If Range("A1") <> "Introduce text" And _
Range("A2") = "Introduce text" And _
Range("A3") <> "Introduce text" Then

Range("A4") = "You should introduce Duration"
Else

If Range("A1") = "Introduce text" And _
Range("A2") <> "Introduce text" And _
Range("A3") ="Introduce text" Then

Range("A4") = "You should introduce Title of the film and Genre"

End if
End if
End if

End Sub

但是,使用 Ifs,我必须为每个可能的组合创建一个条件,如果我引入更多要填充的单元格,这可能需要很长时间。

有没有其他方法可以开发代码?

【问题讨论】:

  • 你需要 VBA 吗?

标签: excel vba


【解决方案1】:

这里不需要 VBA,因为您有一定数量的单元格 (3)。您可以简单地使用一个或多个公式。但是,如果您真的想要 VBA(也许您希望将来能够添加更多单元格),那么下面的代码应该可以工作

Sub Macro1()

  Dim vTitles As Variant
  Dim i As Integer
  Dim iRows As Integer
  Dim sTempSeparator As String
  Dim sToIntroduce As String
  Dim bEventsEnabled As Boolean
  
  vTitles = Array("Title of the film", "Duration", "Genre")
  iRows = UBound(vTitles) + 1
  sTempSeparator = ";" ' anything that is not part of the final text
  
  For i = 1 To iRows
    If Cells(i, 1) = "" Then
      sToIntroduce = Replace(sToIntroduce, sTempSeparator, ",") & sTempSeparator & " " & vTitles(i - 1)
    End If
  Next i

  bEventsEnabled = Application.EnableEvents
  If bEventsEnabled Then Application.EnableEvents = False
  
  With Cells(iRows + 1, 1)
    If Len(sToIntroduce) <> 0 Then
      sToIntroduce = Right$(sToIntroduce, Len(sToIntroduce) - 2)
      sToIntroduce = Replace(sToIntroduce, sTempSeparator, " and")
      sToIntroduce = "You should introduce " & sToIntroduce
      If .Value <> sToIntroduce Then .Value = sToIntroduce
    Else
      If Len(.Value) <> 0 Then .ClearContents
    End If
  End With

  If bEventsEnabled Then Application.EnableEvents = True
  
End Sub

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-07-17
    • 2023-03-09
    • 1970-01-01
    相关资源
    最近更新 更多