2017-09-16 158 views
0

尊敬的用戶#1,VBA的Excel從單元格複製名稱到左邊

我做了一些代碼,需要的名字從單元格複製到左邊,每當這個細胞是空白。

問題是,我只希望代碼在第1行上運行。 當我執行代碼時,它循環遍歷整個工作表。

如何修改它,所以它只能提前執行行動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 

謝謝!

回答

3

如果第一行中的任何單元格是空的,則直到最後一列,下面的代碼將從單元格的文本複製到左側。

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 
+1

該代碼看起來不錯,並且像魅力一樣工作。我已經想用'set WS'更新我的代碼,但你已經找到它了。 Thnx很多! – Dubblej

相關問題