![](/img/trans.png)
[英]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.