如果当前单元格在VBA中为空,则获取相邻单元格的值

时间:2016-06-01 08:13:31

标签: excel vba loops

如果使用 VBA 当前单元格为空,是否可以复制相邻单元格的值?

此处示例:

如果我遍历A列的单元格并且单元格为空,请将B列的相邻单元格的值复制到A列中的空单元格。

enter image description here

这应该是我生成的报告:

enter image description here

3 个答案:

答案 0 :(得分:5)

试试这个:

Sub Demo()
    Dim rng As Range
    Dim lastRow As Long
    Dim cell as Range

    lastrow = Cells(Rows.Count, "A").End(xlUp).Row
    Set rng = Range("A1:A" & lastrow)
    For Each cell In rng
        If cell.Value = "" Then
            cell.Value = cell.Offset(0, 1).Value
        End If
    Next cell
End Sub

答案 1 :(得分:3)

你可以试试这个

Sub main()    
    With ActiveSheet.UsedRange.Columns("A")
        If WorksheetFunction.CountBlank(.Cells) > 0 Then
            .SpecialCells(xlCellTypeBlanks).FormulaR1C1 = "=RC[1]"
            .Value = .Value
        End If
    End With    
End Sub

答案 2 :(得分:2)

Sub movecells()

Dim usedrows As Integer
Dim tmpval As String
Dim i As Integer

usedrows = UsedRange.Rows.Count

For i = 1 To usedrows Step 1

    If Cells(i, 1).Value = "" And Cells(i, 2).Value <> "" Then

        Cells(i, 1).Value = Cells(i, 2).Value
        Cells(i, 2).Value = ""
    End If
Next i
End Sub