使用VBA自动将内容复制到excel中的单元格范围

时间:2013-06-18 12:30:04

标签: excel-vba vba excel

以下是初始 Excel表单

enter image description here

以下是我的输出应该是

enter image description here

我的方法:

  • 从A列获取第一个值

    获取A列的偏移量(0,1)(结果为B1)

    获取B列到第一个空单元格的记录数(结果为3) 将A1的值复制到A1

  • 下面的单元格(记录数 - 1)
  • 循环显示A列中的所有3个值

我已经实现,直到我得到列A中值为单元格的地址。下面是我的代码。

  Dim currentRow As Integer
  Dim element As Variant
  Dim totalRows As String
  Dim offsetrow As String
  Dim offsetcell As Variant

  totalRows = Range("A" & ActiveSheet.Rows.Count).End(xlUp).row
  MsgBox (totalRows)


  For currentRow = 1 To totalRows
    If (IsEmpty(Cells(currentRow, 1).Value)) Then

    Else
        Cells(currentRow, 1).Select
        offsetcell = ActiveCell.Offset(0, 1).Address

        'Do the rest
    End If
  Next

End Sub

感谢任何帮助

3 个答案:

答案 0 :(得分:1)

你可以通过使用数组来优化它,但这是基本的想法:

Dim i As Long

For i = 1 To ActiveSheet.UsedRange.Rows.Count
    If Cells(i + 1, 1).Value = "" And Cells(i, 1).Value <> "" And Cells(i + 1, 2).Value <> "" Then
        Cells(i + 1, 1).Value = Cells(i, 1).Value
    End If
Next

答案 1 :(得分:0)

这是我努力实现所需的输出。这可能不是最有效的方法。无论如何它工作:)。

Sub Button1_Click()

  Dim currentRow As Integer
  Dim totalrows As String
  Dim offsetrow As Integer
  Dim i As Integer
  Dim row As Integer


  totalrows = Range("A" & ActiveSheet.Rows.Count).End(xlUp).row


  For currentRow = 1 To totalrows
    If (IsEmpty(Cells(currentRow, 1).Value)) Then

    Else
        Cells(currentRow, 1).Select
        offsetrow = ActiveCell.Offset(0, 1).row

        row = offsetrow

        i = 1
        Do While (Cells(row, 2).Value <> "")
            i = i + 1
            row = row + 1
            Cells((row - 1), 1).Value = Cells(currentRow, 1).Value

        Loop

    End If
  Next

End Sub

希望这有助于任何人遇到同样的问题。

答案 2 :(得分:0)

只是另一种解决方案:

准确确定范围的行数:

Lastrow = Cells.Find("*", [A1], , , xlByRows, xlPrevious).Row

解决问题的另一种方法:

手册

  1. 在a列中选择范围,
  2. 去空白(ctrl + g),
  3. 按=,向上箭头。现在按住Ctrl + Enter
  4. 复制/粘贴为值...
  5. 以下是执行此操作的代码段:

    Lastrow = Cells.Find("*", [A1], , , xlByRows, xlPrevious).Row
    Range("A1:A" & Lastrow).Select
    Selection.SpecialCells(xlCellTypeBlanks).Select
    Selection.FormulaR1C1 = "=R[-1]C"
    Range("A1:A" & Lastrow).Value = Range("A1:A" & Lastrow).Value
    

    通过循环列B并删除B为空白的A值来完成。

    希望这有帮助。