简体   繁体   中英

Naming the non-empty cells of a column as the previous column's values

So what I want is a button that when pressed will automatically name the right hand column cells the left hand column values, my code at the moment looks something like this,

Private Sub CommandButton1_Click()

    Range("F3").Name = Range("E3")
    Range("F4").Name = Range("E4")
    Range("F5").Name = Range("E5")
    Range("F6").Name = Range("E6")

End Sub

I'm new to using VBA and have looked around a little but couldn't find what I wanted to achieve. Just want a simple solution which can automatically do what my code already does without having to be specific about cell rows. I imagine that there will be either a while or for loop to repeat over many rows and an if statement for the code not running if a cell is empty.

Basically I want the command to run something like below but don't quite know how to write it in excel VBA myself.

for j=3:100
    if F(j) = non empty
        F(j).name = E(j)
    else end
    next j
end

Image below shows the end result :

最终结果

From your sample image this looks like it should work.

Option Explicit

Sub name_eff()
    Dim rw As Long
    With Worksheets("Sheet6")
        For rw = 2 To Application.Min(.Cells(.Rows.Count, "E").End(xlUp).Row, _
                                      .Cells(.Rows.Count, "F").End(xlUp).Row)
            If Application.CountA(.Cells(rw, "E").Resize(1, 2)) = 2 Then _
                .Cells(rw, "F").Name = .Cells(rw, "E").Text
        Next rw
    End With
End Sub

named_ranges

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM