0

我正在用excel写一个宏。我的代码只是通过执行以下操作从电子表格中获取数据块:

Range("E1:O25").Select
Selection.Copy

我可以这样做,因为我知道在这个特定的电子表格上,我想要的值被排序到前 25 行。对于未来的电子表格,我不会知道。

Range("O1").Select
Do Until Selection.Value <> 0
    'get last cell that has a 0 value
     Selection....
Loop
Range("O1: SELECTIONFROMLOOP").Select
Selection.Copy

但我不确定在“选择......”我应该做什么,我在想也许有一个增量变量,但我真的不知道 VBA 最佳实践。有人有建议吗?

4

2 回答 2

1

我真的不喜欢选择一个范围。大多数时候没有必要。我也不想弄乱剪贴板,因为它是“全局”变量的一大块。

如果您只需要将数据从“E1:EX”移动到“O1:OX”,我会执行以下操作。

i = startRow
do while ThisWorksheet.Cells(i,col1).Text <> ""
    thisWorksheet.Cells(i, targetCol).Value = ThisWorksheet.Cells(i,col1).Text
    i = i + 1
loop
于 2013-08-16T16:58:40.293 回答
0

I would do it this way:

Sub duh()
    Dim start As Range: Set start = Range("o1")
    Dim r As Range
    Dim doCopy As Boolean: doCopy = False

    For Each r In Range(start, start.End(xlDown))
        If r.Value <> 0 Then
            If r.Row <> start.Row Then
                Range(start, r.Offset(-1)).Copy
                doCopy = True
            End If
            Exit For
        End If
    Next

    If doCopy Then ActiveSheet.Paste Range("a1")
End Sub

First, we define start as the cell to start at. r will represent the cell that we are evaluating. doCopy will be set to true if the paste will be done (false if we have nothing to copy).

The For Each r... loop will iterate through every cell from start through the bottom of the column (this may not be exactly what you want....)

When we find a non-zero value, first check to see if we're still on the first row. If we are, then we'll just exit the loop. If we're not on the first row, then Range(start, r.Offset(-1)).Copy will copy to the clipboard the range starting at start and ending at the cell above r; set doCopy to True and exit the loop. Finally, do the paste only if doCopy is True.

于 2013-08-16T17:21:13.057 回答