简体   繁体   中英

VBA Excel copy name from cell to the left

Dear Stackoverflow users,

I made some code, that needs to copy the name from the cell to the left, whenever this cell is blank.

The problem is that i only want the code to be ran on row 1. When i execute the code it loops through my whole worksheet.

How can i modify it, so it only performs the action for row 1.

Sub Test()

Dim LastCol As Integer
Dim WS As ActiveSheet

With WS
    LastCol = .Cells(1, .Columns.Count).End(xlToLeft).Column
End With

    For i = 2 To LastCol
            If WS.Cells(1, i) = Empty Then
                 WS.Cells(1, i).SpecialCells(xlCellTypeBlanks).FormulaR1C1 = "=RC[-1]"
            End If
    Next i

End Sub

Thanks in advance!

Below code will copy text from cell to the left if any cell in the first row is empty till the last column.

Sub Test()
    Dim LastCol As Integer
    Dim WS As Worksheet

    Set WS = ThisWorkbook.Sheets("Sheet3")  'change Sheet3 to your data sheet

    With WS
        LastCol = .Cells(1, .Columns.Count).End(xlToLeft).Column
        For i = 2 To LastCol
            If IsEmpty(.Cells(1, i)) Then
                .Cells(1, i).Value = .Cells(1, i).Offset(0, -1).Value
            End If
        Next i
    End With
End Sub

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