Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
412 views
in Technique[技术] by (71.8m points)

vba - Creating a symmetric matrix

I want to learn how to create a symmetric matrix in VBA. For example in the first step I want to choose Range("C3:I3") then copy to the Range("B4:B10"). In the second stage it should choose Range("D4:I4") then copy to the Range("C5:C10"). It should go on like that.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I have some code to do it. Your selected cell must be within the range of numbers.

1. If the diagonal line is empty.

enter image description here ? enter image description here

The code:

Sub making_symmetric_matrix()

Dim i As Long, j As Long
Dim rng As Range
Set rng = Selection.CurrentRegion
Dim rngStart As Range
Set rngStart = Cells(rng.Row, rng.Column - 1)

For i = 1 To rng.Rows.Count
    For j = i To rng.Columns.Count
        rngStart.Offset(j, i - 1).Value = rngStart.Offset(i - 1, j).Value
    Next
Next

End Sub


2. If the diagonal line is not empty.

enter image description here ? enter image description here

The code:

Sub making_symmetric_matrix2()

Dim i As Long, j As Long
Dim rng As Range
Set rng = Selection.CurrentRegion
Dim rngStart As Range
Set rngStart = Cells(rng.Row, rng.Column)

For i = 1 To rng.Rows.Count
    For j = i To rng.Columns.Count
        rngStart.Offset(j - 1, i - 1).Value = rngStart.Offset(i - 1, j - 1).Value
    Next
Next

End Sub

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...