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

.End(xlDown) selecting last nonblank cell incorrectly

正在编写VBA代码以将动态范围复制到新作品sheet。该代码应该首先定义一个范围,该范围是要复制的范围。它通过从范围开始的左上角开始,然后使用 Range.End(xlDown) 找到最后一个条目来实现这一点。然后偏移量找到范围的右下角,范围设置为从左上角到右下角。这就是 应该 工作的方式,以及它如何用于逐字记录的工作方式,为了清楚起见,唯一的变化是变量名称。

这是它向南走的地方。 Range.End(xlDown) 表示该列中的最后一个非空白单元格是作品中非常非常底部的单元格sheet(例如第 40,000 行)。这显然不是真的,因为最后一个非空白单元格比我正在查看的范围低三行。因此,我得到的不是 4x5 的尺寸范围,而是几乎跨越 sheet 的整个高度。我也尝试清除列的所有格式以防万一,但无济于事。代码如下。

    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").End(xlDown).Offset(0, 3)
    Set EnclosureStarters = IOws.Range("$Z", BottomLine)

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

    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").Value
                .BorderAround _
                ColorIndex:=1, Weight:=xlThin
                .HorizontalAlignment = xlCenter
            End With
        Next EnclosureNumber

    End Sub

如有任何建议,我们将不胜感激,这令人沮丧不已。如果我需要 post 错误照片或任何进一步的代码等,请告诉我。

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

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

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

Cleaner 再次使用 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