Home » excel » excel – How to go through a range and fill another worksheet's cells with the values?

# excel – How to go through a range and fill another worksheet's cells with the values?

Questions:

In my Excel worksheet I have something like this:

``````          1      2      3
John   Paul   Mike
1  John   0      1      1
2  Paul   1      0
3  Mike   1             0
``````

Which is similar to a symmetric matrix. Note that:

• Each person has an ID;

• For simplification, I set the values to 1’s, but they can go from 1
to 20. 0’s will always be 0’s. There are also some blank spaces.

What I need is a macro that goes through the “matrix” and outputs the values into another worksheet in the following format:

``````From     To     Strenght
1      2        1
1      3        1
2      1        1
3      1        1
``````

This is what I have so far, but isn’t working because it return the error “The object is required”, pointing to `strenghts`.

``````Dim i As Integer, j As Integer, strenghts As Integer

Set currentCell = Worksheets("Raw_Relationships").Cells(3, 3)

For i = 1 To 145
For j = 1 To 145

If currentCell <> "" Then

Set currentCell = Worksheets("Raw_Relationships").Cells(i, j).Offset(2, 3)
Set strenghts = Worksheets("Raw_Relationships").Cells(i, j).Offset(2, 2).Value

Set Worksheets("Gephi_Data").Cells(i, 1).Offset(150, 0).Value = i
Set Worksheets("Gephi_Data").Cells(i, 2).Offset(150, 0).Value = j
Set Worksheets("Gephi_Data").Cells(i, 3).Offset(150, 0).Value = strenghts

End If

Next j
Next i
``````

Any tips on how to do this?

There are many ways to achieve what you want. Here is a very basic example of what you want.

Let’s say your sheet looks like this

Use this code. I have commented the code so that you shouldn’t have a problem understanding it. If you do then simply ask 🙂

Code

``````Option Explicit

Sub Sample()
Dim ws As Worksheet
Dim i As Long, j As Long
Dim rw As Long, col As Long

'~~> Change this to the relevant sheet
Set ws = ThisWorkbook.Sheets("Sheet1")

'~~> This is where the output will be generated
rw = 2: col = 8

With ws
.Cells(1, col).Value = "From"
.Cells(1, col + 1).Value = "To"
.Cells(1, col + 2).Value = "Strength"

'~~> Looping through rows
For i = 3 To 5
'~~> Looping through columns
For j = 3 To 5
'~~> Check if the cell is > 0
If .Cells(i, j).Value > 0 Then
'~~> Write the `From` column
.Cells(rw, col).Value = .Cells(i, 1).Value
'~~> Write the `To` Column
.Cells(rw, col + 1).Value = .Cells(1, j).Value
'~~> Write the `Strength` Column
.Cells(rw, col + 2).Value = .Cells(i, j).Value
rw = rw + 1
End If
Next j
Next i
End With
End Sub
``````

Output

I am generating the output in Col `H` onwards. Change as applicable.

Get rid of `Set` in `Set strenghts = ...`. Just write `strenghts = ...`. `Set` is only used to set references to objects. `strenghts` isn’t an object, it’s a numeric value.
Also, I’m not sure if the typo in `strenghts` is intentional, but it’s usually spelled “strengths”.