2

我放弃。我只花了四个小时试图弄清楚为什么这个宏不起作用。我希望它采用给定的源范围,使用循环遍历它For并将值复制到不同的列。

我希望它从给定的目标单元格开始,并且

  • 输入值
  • 使用插入创建一个新行(整行,而不仅仅是插入该列。我想将数据放入现有的一组行中)
  • 不覆盖指定目标列终点的标记。它下面有需要保存的数据。

我不知道为什么

  • 在一个过程实例中,它输入值,然后在插入下一行时清除数据。
  • 在第二种情况下,它会跳过一行并删除列标记的结尾

请注意,我不是在寻找聪明、优雅的问题解决方案,为了自学范式,我想保持基本的东西。随着我对基础知识的理解越来越好,我将尝试一些高级技巧。

TIA

Sub Macro1()
Dim firstRow As Range, lastRow As Range
Dim source As Range, destination As Range
Dim readCell As Range

Set firstRow = Range("F2")
Set lastRow = Range("F20")
Set destination = Range("A21")


Set source = Range(firstRow.Address(False, False) & ":" & lastRow.Address(False, False))

For Each readCell In source
    destination.Select
    destination.Value = readCell.Value

    If (readCell.Address(False, False) = lastRow.Offset(1, 0)) Then
        Exit For
    Else
       'destination.Select
    End If

    'MsgBox (destination.Value)
    destination.EntireRow.Insert Shift:=xlUp
    Set destination = destination.Offset(1, 0)
Next
End Sub
4

2 回答 2

1

Very commendable that you want to understand as well as solve

It is easier to use a row counter than increments from a fixed destination. This minor adjustment

  • avoids Select
  • uses a counter, lngRow, to control the new row and new values

    code

    Sub Macro1()
    Dim readCell As Range
    Dim lngRow As Long
    For Each readCell In Range("F2:F20")
        [a21].Offset(lngRow, 0).EntireRow.Insert Shift:=xlUp
        [a21].Offset(lngRow, 0).Value = readCell.Value
        lngRow = lngRow + 1
    Next
    End Sub
    
于 2012-09-18T08:28:52.773 回答
1

这里有一些提示:

鉴于firstRowandlastRow是单细胞,不需要这些Address东西。利用

Set source = Range(firstRow,  lastRow)

destination.EntireRow.Insert Shift:=xlUp中,因为您申请Insert的是整行,Shift所以没有区别。利用

destination.EntireRow.Insert

插入的行放置在上方destination,并向destination下移动。所以 for 循环的第一次迭代就是这样做的

  1. 设置destinationA21
  2. 插入行,转移destinationA22
  3. 设置desination一行,即A23

然后下一次迭代将覆盖原来在 中的数据A22,现在在A23

我想你想要

Sub Macro1()
    Dim firstRow As Range, lastRow As Range
    Dim destination As Range
    Dim readCell As Range

    Set firstRow = Range("F2")
    Set lastRow = Range("F20")
    Set destination = Range("A21")

    For Each readCell In Range(firstRow, lastRow)
        destination.Value = readCell.Value
        destination.EntireRow.Offset(1, 0).Insert
        Set destination = destination.Offset(1, 0)
    Next
End Sub
于 2012-09-18T08:28:04.230 回答