.End(xlDown)错误地选择最后一个非空白单元格

时间:2015-08-07 18:28:22

标签: excel vba excel-vba dynamic

编写VBA代码以将动态范围复制到新工作表。该代码应该首先定义一个范围,该范围是要复制的范围。它通过从范围开始的左上角开始,然后使用Range.End(xlDown)查找最后一个条目来完成此操作。然后偏移量找到范围的右下角,范围设置为从左上角到右下角。这就是假设的工作方式,以及它如何为逐字子工作,其中唯一的变化是变量名称以便清楚。

这是它向南的地方。 Range.End(xlDown)表示列中的最后一个非空单元格是工作表上非常非常底部的单元格(如40,000行一样)。这显然不正确,因为最后一个非空白单元格是我正在查看的范围内的三行。因此,我得到一个横跨纸张整个高度的尺寸范围,而不是4x5尺寸范围。我也尝试清除列的所有格式,以防有些事情挥之不去,但无济于事。代码如下。

    Sub Copy_Starters_ToMaster()

    Dim MasterIO As Worksheet, IOws As Worksheet
    Set MasterIO = Worksheets("Master IO Worksheet")
    Set IOws = Worksheets("IO Worksheet")

    'Sets a range to cover all VFDs entered for an enclosure.
    Dim EnclosureStarters As Range, BottomLine As Range
    Set BottomLine = IOws.Range("$Z$6").End(xlDown).Offset(0, 3)
    Set EnclosureStarters = IOws.Range("$Z$6", BottomLine)

    'Finds first blank line in Master VFD table
    Dim myBlankLine As Range
    Set myBlankLine = MasterIO.Range("$AB$6")

    Do While myBlankLine <> vbNullString
       Set myBlankLine = myBlankLine.Offset(1, 0)
    Loop

    'Copies over enclosure list of VFDs, pastes into the master at the bottom of the list.
    EnclosureStarters.Copy
    myBlankLine.PasteSpecial
    Dim BottomInEnclosure As Range, currentStarterRange As Range, EnclosureNumber As Range

    'Indicates which enclosure each VFD copied in belongs to, formats appropriately.
    Set BottomInEnclosure = myBlankLine.End(xlDown)
    Set currentStarterRange = Range(myBlankLine, BottomInEnclosure).Offset(0, -1)
        For Each EnclosureNumber In currentStarterRange
            With EnclosureNumber
                .Value = Worksheets("Math Sheet").Range("$A$11").Value
                .BorderAround _
                ColorIndex:=1, Weight:=xlThin
                .HorizontalAlignment = xlCenter
            End With
        Next EnclosureNumber

    End Sub

对此的任何建议都将非常感激,它无穷无尽地令人沮丧。如果我需要发布错误的照片或任何其他代码等,请告诉我。

2 个答案:

答案 0 :(得分:0)

我认为这里的答案是使用xlUp和一般的lastrow公式,例如:

Set BottomLine = IOws.Cells(Rows.Count, "Z").End(xlUp).Offset(0, 3)

它给出Z列中最后使用的单元格,偏移3

答案 1 :(得分:0)

再次使用清除器来使用Find而不是依赖xlUp类型的快捷方式,类似于此(它也适用于列为空,这是设置范围时的常见错误):

Dim rng1 As Range
Set rng1 = IOws.Range("Z:Z").Find("*", IOws.[z1], xlFormulas, , xlPrevious)
If Not rng1 Is Nothing Then Set Bottomline = rng1.Offset(0, 3)
`if rng1 is Nothing then the area searched is blank