2017-09-16 156 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

相关问题