在col A中找到非空单元格并将内容移动到col B

时间:2016-03-08 09:45:38

标签: excel-vba excel-formula vba excel

我在excel中有两列文本,cols A和B.

我需要一个函数或vb代码来遍历col A中的每个单元格,找到一个非空的单元格,例如A21,将该单元格的内容移动到B22。

然后从A23开始继续搜索。

col A中数据的行数可能是几千长。

如何解决这个问题?

感谢您的帮助。

4 个答案:

答案 0 :(得分:0)

您可以通过编写VBA代码来解决此问题

Sub moveColAToColB()
  Dim currentSheet As Worksheet
  Set currentSheet = Sheets("Sheet1")
  Dim l As Long

  With currentSheet
    For l = 1 To.Rows.Count
      If Not IsEmpty(.Cells(l, 1).Value) Then
          .Cells(l, 2).Value = .Cells(l, 1).Value
      End If
    Next l
  End With
End Sub

编辑:我认为你在描述中犯了一个错误,但我认为你不能对简单的代码进行简单的修改......

Sub moveColAToColB()
  Dim currentSheet As Worksheet
  Set currentSheet = Sheets("Sheet1")
  Dim l As Long

  With currentSheet
    For l = 1 To.Rows.Count
      If Not IsEmpty(.Cells(l, 1).Value) Then
          .Cells(l + 1, 2).Value = .Cells(l, 1).Value
      l = l + 1
      End If
    Next l
  End With
End Sub

答案 1 :(得分:0)

参见代码:

Sub MoveCellsFromColATOColB()

  For x = 21 To ActiveSheet.UsedRange.SpecialCells(xlCellTypeLastCell).Row ' here is the start range declared also used range

    Cells(x + 1, "B").Value = Cells(x, "A").Value

  Next x

End Sub

结果:
enter image description here

祝你好运

丹尼尔

答案 2 :(得分:0)

试试这个:

Sub test()

Dim lastrow As Integer

lastrow = ActiveSheet.Cells(ActiveSheet.Rows.Count, "A").End(xlUp).Row

Range("A1").Select

While ActiveCell.Row <= lastrow

If ActiveCell.Value = "" Then

ActiveCell.Offset(1, 0).Select

Else

ActiveCell.Offset(1, 1).Value = ActiveCell.Value

ActiveCell.Offset(2, 0).Select

End If

Wend

Range("A1").Select

End Sub

结果如下:

enter image description here

答案 3 :(得分:0)

考虑:

Sub MoveData()
    Dim K As Long, nA As Long
    Dim i As Long

    nA = Cells(Rows.Count, "A").End(xlUp).Row
    K = 22

    For i = 1 To nA
        If Cells(i, "A").Value <> "" Then
            Cells(K, "B").Value = Cells(i, "A").Value
            K = K + 1
        End If
    Next i
End Sub

例如:

enter image description here