[英]VBA function to iterate through cells, replacing a cell with the relative column header value
I'm trying to convert a data matrix to a new standard that should fit a specific analysis software. 我正在尝试将数据矩阵转换为适合特定分析软件的新标准。
The initial matrix looks like this: 初始矩阵如下所示:
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
I've been trying to achieve this: 我一直在努力实现这一目标:
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
Essentially, what I'm trying to do is: 本质上,我想做的是:
1. For every column, look in every cell for a number other than 0; 1.对于每一列,在每个单元格中查找非0的数字;否则,返回0。
2. If this condition is achieved, replace the cell value with the relative "state" header. 2.如果达到此条件,则用相对的“状态”标题替换单元格值。 Meaning, for instance, if A4 <> 0, then replace it with A3 value. 例如,如果A4 <> 0,则将其替换为A3值。
The code I've used is as follows: 我使用的代码如下:
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
It works fine in a defined range of one single column, but I'm having trouble making it dynamic. 它可以在一列的定义范围内正常工作,但是我很难使其动态化。 Should I use R1C1 notation to refer to the cells in the range? 我应该使用R1C1表示法来引用范围内的单元格吗? Everything related that I could find never explicits how to make this iteration more flexible. 我找不到的所有相关内容都没有明确说明如何使此迭代更加灵活。 Should I use nested loops? 我应该使用嵌套循环吗? Loops are a very difficult thing for me to grasp, still, so, please be patient. 对于我来说,循环是一件非常困难的事情,因此,请耐心等待。
I'd appreciate if anyone could point me to the right direction. 如果有人能指出我正确的方向,我将不胜感激。 Thanks! 谢谢!
I am assuming that there is nothing else on each sheet than the matrix in question. 我假设除了所讨论的矩阵外,每张纸上都没有其他内容。 In that case you should be able to make you procedure dynamic by modifying your code like the following: 在这种情况下,您应该能够通过修改代码来使过程动态化,如下所示:
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
This will loop through each column and each row in your matrix if you have defined in what cell the most left state value is located. 如果您定义了最左状态值位于哪个单元格中,则它将遍历矩阵的每一列和每一行。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.