excel - 如何根据另一列单元格中的条目更新列中的单元格?
问题描述
如果 C 列包含“100”,则 D 列应更新为“001”。
如果 C 列包含“101”,则 D 列应更新为“002”。
这是 C 列中的单元格区域所必需的。
我尝试了下面的代码,但它不起作用。
Sub iflocation()
If activecell.Range("c1:C").Value = 100 Then Range("d1"d").Value = Range "001.Value
If activecell.Range("c1:C").Value = 101 Then Range("d1"d").Value = Range "002.Value
End sub
解决方案
内存的最快方法之一是将整列添加到数组中。遍历列并保存行索引,这在集合中满足您的条件。
Sub MainSub()
Dim vArr As Variant
Dim i As Long
'collection contains row indexes, where the value in column C = 100
Dim col100 As New Collection
'collection contains row indexes, where the value in column C = 101
Dim col101 As New Collection
Dim wsh As Worksheet
Dim itm As Variant
Set wsh = Sheets("Sheet1")
vArr = wsh.Columns("C:C")
'iterate through the array and collect corresponding indexes
For i = LBound(vArr) To UBound(vArr)
If CStr(vArr(i, 1)) = "100" Then
col100.Add i
ElseIf CStr(vArr(i, 1)) = "101" Then
col101.Add i
End If
Next i
'call function which sets predefined value into column D
SetNewValueInColumnD wsh, col100, "001"
SetNewValueInColumnD wsh, col101, "002"
End Sub
Private Sub SetNewValueInColumnD(ByRef wsh As Worksheet, ByRef p_col As Collection,
ByRef p_value As String)
Dim itm As Variant
For Each itm In p_col
With wsh.Range("D" & itm)
.NumberFormat = "@"
.Value2 = p_value
End With
Next itm
推荐阅读
- javascript - React Hooks useEffect 不会使用正确的状态
- swift - 从 firebase 获取数据到 struct
- django - 发布表单时将当前用户设置为模型
- php - 为什么 true != 'none' 等于 false?
- python - pybind11 运行测试用例
- javascript - 在谷歌应用程序脚本中错误地声明当前单元格变量
- c++ - 在 Z3 中使用位向量文字
- python - 计算多项式 logit 模型预测概率
- javascript - Summernote 将“文件”字段添加到 POST
- sql - 设计数据库,其中表的主键也是另一个表的外键