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

编写VBA代码以将dynamic范围复制到新工作表。 代码应该首先定义一个范围,这是要复制的范围。 它通过从范围开始的左上angular开始,然后使用Range.End(xlDown)来查找最后一个条目。 偏移量然后find范围的右下angular,范围设置为从左上angular到右下angular。 这是它应该如何工作,以及它如何工作的逐字sub,其中唯一的变化是在variables名称为清晰。

这是南下的地方。 Range.End(xlDown)指示列中最后一个非空白单元格是工作表上非常非常底部的单元格(如行40,000个东西)。 这显然是不正确的,因为最后一个非空白单元格距离我所看到的范围有三行。 因此,我不是得到一个4×5大小的范围,而是得到一个几乎覆盖整个表格高度的范围。 我也尝试清除列的所有格式,以防万一有什么徘徊,但无济于事。 代码如下。

  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 

任何意见,将不胜感激,这是无止境的挫折。 请让我知道是否需要发布错误的照片,或任何进一步的代码等。

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

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

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

再次使用清理器来Find而不是依赖xlUptypes的快捷方式,就像这样(这也适用于空列,这是设置范围时常见的错误):

 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