提问人:Fenja Seidel 提问时间:11/6/2023 最后编辑:IkeFenja Seidel 更新时间:11/6/2023 访问量:32
如何在 Word 中创建一个根据文本输入改变颜色的表格?
How do I create a table in word that changes color depending on the text input?
问:
我正在尝试制作一个可以分配三个值的表: “无冲突”(绿色背景)、“轻微冲突”(黄色背景)和“大冲突”(红色背景)通过下拉菜单。通过开发人员工具,我能够找到下拉菜单并对其进行相应的配置。现在我想我可以使用单词的“宏”功能来促进表格本身的颜色变化。 我使用了我在另一个线程上找到并编辑的以下代码,但不知何故它没有做它应该做的事情......
不知道为什么下面的代码不完全在这个框中......
Option Explicit
Sub Farbänderung()
Dim tTable As Table
Dim cCell As Cell
For Each tTable In ActiveDocument.Range.Tables
For Each cCell In tTable.Range.Cells
If InStr(cCell.Range.Text, "no conflicts") <> 0 Then
Selection.Shading.Texture = wdTextureNone
Selection.Shading.ForegroundPatternColor = wdColorAutomatic
Selection.Shading.BackgroundPatternColor = wdColorGreen
Else
If InStr(cCell.Range.Text, "slight conflict") <> 0 Then
Selection.Shading.Texture = wdTextureNone
Selection.Shading.ForegroundPatternColor = wdColorAutomatic
Selection.Shading.BackgroundPatternColor = wdColorYellow
Else
If InStr(cCell.Range.Text, "big conflict") <> 0 Then
Selection.Shading.Texture = wdTextureNone
Selection.Shading.ForegroundPatternColor = wdColorAutomatic
Selection.Shading.BackgroundPatternColor = wdColorRed
End If
End If
Next
Next
End Sub
无论输入值如何,此函数都将每个选定字段设置为绿色。
有人可以帮我吗?最终目标是将其以可填写的单词形式呈现,因此,如果它可以像 excel 中的条件编程一样自动化,那将是理想的,但我确实满足于一个功能正常的宏 ;-)
答:
0赞
Ike
11/6/2023
#1
代码存在两个主要问题:
- 你的 If 结构是错误的 - 你应该收到一个编译错误。查看有关如何使用的文档
ElseIf
- 您将背景颜色应用于所选内容 - 而不是您正在检查的单元格
此外,如果没有必要,最好不要重复代码。
我解决了这些问题:
Sub Farbänderung()
Dim tTable As Table
Dim cCell As Cell, color As WdColor
For Each tTable In ActiveDocument.Range.Tables
For Each cCell In tTable.Range.Cells
With cCell
If InStr(.Range.Text, "no conflicts") <> 0 Then
color = wdColorGreen
ElseIf InStr(cCell.Range.Text, "slight conflict") <> 0 Then
color = wdColorYellow
ElseIf InStr(cCell.Range.Text, "big conflict") <> 0 Then
color = wdColorRed
Else
color = wdColorAutomatic
End If
If color <> wdColorAutomatic Then
With .Shading
.Texture = wdTextureNone
.ForegroundPatternColor = wdColorAutomatic
.BackgroundPatternColor = color
End With
End If
End With
Next
Next
End Sub
评论
0赞
Fenja Seidel
11/6/2023
非常感谢!!!!我是一个完全的初学者,完全迷失了......有没有办法在每次更改值时自动运行代码?(因此,如果我将值从“无冲突”更改为“大冲突”,颜色会自动更改,而无需再次手动运行宏?
0赞
Ike
11/6/2023
看这里: stackoverflow.com/a/54917202 (如果我的答案对你有帮助:别忘了接受它:-))
0赞
Fenja Seidel
11/6/2023
对不起,该链接对我没有帮助...有没有其他方法(解释或这样做)?...对不起,英语不是我的第一语言,我对此非常陌生
评论