[英]Looping through cells by column and converting each current cell value to new cell values through a function (Excel VBA)
[英]VBA function to iterate through cells, replacing a cell with the relative column header value
我正在尝试将数据矩阵转换为适合特定分析软件的新标准。
初始矩阵如下所示:
real char num 10 10 25 26 26 56
--------------------------------
state num 1 2 9 4 6 3
--------------------------------
name 1 0 0 1 1 0 1
name 2 1 0 0 0 0 0
name 3 0 1 1 0 0 1
name 4 0 1 0 0 1 0
name 5 1 0 0 0 0 0
name 6 0 0 1 0 1 0
我一直在努力实现这一目标:
real char num 10 10 25 26 26 56
--------------------------------
state num 1 2 9 4 6 3
--------------------------------
name 1 0 0 9 4 0 3
name 2 1 0 0 0 0 0
name 3 0 2 9 0 0 3
name 4 0 2 0 0 6 0
name 5 1 0 0 0 0 0
name 6 0 0 9 0 6 0
本质上,我想做的是:
1.对于每一列,在每个单元格中查找非0的数字;否则,返回0。
2.如果达到此条件,则用相对的“状态”标题替换单元格值。 例如,如果A4 <> 0,则将其替换为A3值。
我使用的代码如下:
Sub Iterate_replace()
Sheets("matrix").Select
Dim r As Range, cell As Range, state As Range
Set r = Range("C3")
Set state = Range("C2")
For Each cell In r
If cell.Value <> "0" Then
cell.Value = state.Value
End If
Next
End Sub
它可以在一列的定义范围内正常工作,但是我很难使其动态化。 我应该使用R1C1表示法来引用范围内的单元格吗? 我找不到的所有相关内容都没有明确说明如何使此迭代更加灵活。 我应该使用嵌套循环吗? 对于我来说,循环是一件非常困难的事情,因此,请耐心等待。
如果有人能指出我正确的方向,我将不胜感激。 谢谢!
我假设除了所讨论的矩阵外,每张纸上都没有其他内容。 在这种情况下,您应该能够通过修改代码来使过程动态化,如下所示:
Sub Iterate_replace()
Sheets("matrix").Select
Dim i As Integer, j As Integer
Dim state As Range
Set state = Range("C2")
'Loops through each row and each column in matrix
For i = state.Column To ActiveSheet.Cells(state.Row, Columns.Count).End(xlToLeft).Column
For j = state.Row + 1 To ActiveSheet.Cells(Rows.Count, state.Column).End(xlUp).Row
If Cells(j, i).Value <> 0 Then
Cells(j, i).Value = Cells(state.Row, i).Value
End If
Next j
Next i
End Sub
如果您定义了最左状态值位于哪个单元格中,则它将遍历矩阵的每一列和每一行。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.