我使用完全相同的代码来命名两个工作簿中的动态范围。在将其实现到Workbook 111中的通用代码主体之前,我使用Workbook TestBook1测试代码。
守则是:
Dim HDaER As Worksheet
Dim HDaERReturnLR As Long
Dim HDaERReturnLC As Long
Dim HDaERReturnsDNR As Range
Dim HDaERReturns As String
Set HDaER = Sheets("HistoricalDataandExcessReturns")
With HDaER.Cells(108, 2).CurrentRegion
HDaERReturnLR = .Find(What:="*", After:=HDaER.Cells(107, 1), _
LookIn:=xlFormulas, LookAt:=xlPart, _
SearchOrder:=xlByRows, SearchDirection:=xlPrevious).row
HDaERReturnLC = .Find(What:="*", After:=HDaER.Cells(107, 1), _
LookIn:=xlFormulas, LookAt:=xlPart, _
SearchOrder:=xlByColumns, SearchDirection:=xlPrevious).Column
Set HDaERReturnsDNR = HDaER.Range(HDaER.Cells(108, 2), _
HDaER.Cells(HDaERReturnLR, HDaERReturnLC))
End With
HDaER.Names.Add Name:="HDaERReturns", RefersTo:=HDaERReturnsDNR
Range("HDaERReturns").Select我在TestBook1中得到的输出是准确的:

和我在工作簿111中获得的输出是不准确的:

我做错什么了?
发布于 2018-03-10 11:34:40
您的整个代码可能会折叠为以下代码
With Sheets("HistoricalDataandExcessReturns").Cells(107, 1)
With .Parent.Range(.End(xlDown), .End(xlToRight))
.Parent.Names.Add name:="HDaERReturns", RefersTo:=.Resize(.Rows.Count - 1, .Columns.Count - 1).Offset(1, 1)
End With
.Range("HDaERReturns").Select
End With发布于 2018-03-10 10:53:27
规范After:=HDaER.Cells(...)显示为起点..。在本例中,我使用了After:=HDaER.Cells(107, 1),但我在HDaER.Cells(105, 1)中使用了标头“波动性”,这意味着用行With HDaER.Cells(108, 2).CurrentRegion指定范围的起始单元格,并包括方向SearchDirection:=xlPrevious的另一个规范,导致将HDaER.Range(HDaER.Cells(108, 2), HDaER.Cells(105, 1))标记为要命名的动态范围。
具有精确输出的代码是:
Dim HDaER As Worksheet
Dim HDaERReturnLR As Long
Dim HDaERReturnLC As Long
Dim HDaERReturnsDNR As Range
Dim HDaERReturns As String
Set HDaER = Sheets("HistoricalDataandExcessReturns")
With HDaER.Cells(108, 2).CurrentRegion
HDaERReturnLR = .Find(What:="*", After:=HDaER.Cells(105, 1), _
LookIn:=xlFormulas, LookAt:=xlPart, _
SearchOrder:=xlByRows, SearchDirection:=xlPrevious).row
HDaERReturnLC = .Find(What:="*", After:=HDaER.Cells(105, 1), _
LookIn:=xlFormulas, LookAt:=xlPart, _
SearchOrder:=xlByColumns, SearchDirection:=xlPrevious).Column
Set HDaERReturnsDNR = HDaER.Range(HDaER.Cells(108, 2), _
HDaER.Cells(HDaERReturnLR, HDaERReturnLC))
End With
HDaER.Names.Add Name:="HDaERReturns", RefersTo:=HDaERReturnsDNR
Range("HDaERReturns").Select以HDaER.Cell(105, 1) After:=HDaER.Cells(105, 1)**,作为起点的的将导致精确的** .Range 选择.

回答@DisplayName的评论和答复:
好主意,坏输出..。
MsgBox最后一行显示此结果:

MsgBox最后一列显示此结果:

代码输出(正如我先前回答的那样):

准确的代码输入:

https://stackoverflow.com/questions/49207839
复制相似问题