[英]How to replace cell info in excel conditionaly with another cell info from another sheet regarding to another cell value
[英]How to replace styles of an Excel sheet cell with no style and then add value to cell?
我继承了一个 Excel 工作表(来自以前的员工),它使用背景颜色来传达信息,而不是在单元格中放置值。
更新:我应该提到,虽然文档是 Excel 表格,但我们的办公室正在为我们的套件使用 LibreOffice。 我认为 LibreOffice 使用 StarBasic 而不是 VBscript。
目前,这张 Excel 表格只能用人眼查看,但很快这张表格将被输入到更大的系统中。 对于工作表中的这个特定列来说,拥有实际数据而不仅仅是样式会更有意义。
如何根据单元格的样式搜索/替换一列数据中的所有单元格,并在背景颜色的位置添加一个值。
我希望能够做的非常粗略的伪代码:
for each ( cell in column-X of sheet(1) ) {
if cell.background.color == BLACK {
cell.background.color = NO_BACKGROUND_COLOR
cell.value = "false"
}
}
假设所需的细胞的变化仅影响color
和contents
的的cells
。
如果之前进行了一些计划,可以在一次运行中完成所有更改,并使用如下信息表:
| Actual | Color | Change |
为了以图形方式解释如何获取要替换的colors
,让我们假设下图表示我们需要应用更改的表格:
为了确定单元格的color
,我们将使用即时窗口。
在 VBA 编辑器中,按 Ctrl+G 打开立即窗口。
在 Excel 中选择一个要替换的color
单元格。
在立即窗口中输入?activecell.interior.color
以获得单元格的color
。
对每种color
重复。
此表完成。
我们将使用Select Case 语句来应用带有每种color
操作的表格
Sub Cell_Color_Replace()
Dim rTrg As Range
With ThisWorkbook.Sheets("DATA")
Rem To set all used cells in the worksheet as the target range
Set rTrg = .UsedRange
Rem A method to set the range
Set rTrg = .UsedRange.Columns(11)
Rem Another method to set the range
Set rTrg = .Range("K7:K30")
End With
Call Cell_Color_Replace_APPLY(rTrg)
End Sub
…
我在两个过程中破坏了该方法,因此可以从任何其他过程调用下面的关键过程。
Sub Cell_Color_Replace_APPLY(rTrg As Range)
Dim rCll As Range
Dim vValue As Variant 'variant to allow different datatypes
For Each rCll In rTrg.Cells
With rCll
Select Case .Interior.Color
Case 13561798: vValue = True
Case 13551615: vValue = "BAD"
Case 10284031: vValue = 1234
Case Else: vValue = "¡NOACTION"
End Select
If vValue <> "¡NOACTION" Then
.Interior.Pattern = xlNone
.Value = vValue
End If
End With: Next
End Sub
这是调整的范围,注意我使用的样式包括font.color
格式,所以方法的性能是可见的。
您的“伪代码”绝对是正确的。
我不得不自己做一次类似的事情 - 尝试下面的方法,它很粗糙,但应该可以解决问题;
Sub ChangeBackground()
Dim MacroRange as Range
Set MacroRange = Activesheet.Range("A:A") 'replace this with whatever range you want the macro to affect,
' I originally just used ActiveSheet.Usedrange to do the whole sheet
Dim rngCell As Range
Dim Colour As Long
Colour = Selection.Interior.Color
Debug.Print Colour
For Each rngCell In ActiveSheet.MacroRange
If rngCell.Interior.Color = Colour Then
rngCell.Interior.ColorIndex = 0 'no fill
rngCell.value = "Value" 'insert desired value here
End If
Next
End Sub
注意这Activesheet
使用Activesheet
和Selection
!! (我知道糟糕的形式,但我不得不做一次完全相同的事情,这只是当时最快的方式)。 在启动此宏之前,您需要激活所需的工作簿和工作表,并选择具有要替换颜色的单元格。
在我的情况下,我有多种颜色要替换,但一次只替换一种(它们需要不同的值),因此Selection
元素来选择颜色。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.