我正在尝试定义一个可变列范围,该范围将通过已知的第一个单元格设置,最后一个单元格是包含" Net Amount"
Dim cell As Object
Dim P1RNG As Range
Dim PFRNG As Range
Dim PRNG As Range
Worksheets("Sales Orders").Activate
For Each cell In Sheet1.Cells
If cell.Value = "Q300103176" Then
'Find first Part number
Set P1RNG = cell.Offset(29, -24)
'Find Last Part Number
Set PFRNG =
'Set part number range
Set PRNG = Range("P1RNG":"PFRNG")
PRNG.Select
End If
Next
到目前为止我已编写的代码我还不知道如何找到范围内的最终单元格(PFRNG),它将位于包含&#34的单元格的正上方;净金额"。我不能找到包含"净金额"并使其偏移一个,因为此工作表中有多个包含净金额的单元格。它必须特别是第一个细胞(P1RNG)下面的那个。 如果不使用我所做的任何我可以学习的代码,也可能有更好的方法来做到这一点。
答案 0 :(得分:1)
您可以使用带有偏移量的 Find():
Sub PartOfColumn()
Dim B As Range, Startt As Range, WhatToFind As String
Dim rTemp As Range
Set B = Range("B:B")
Set Startt = Range("B5")
WhatToFind = "Net Amount"
Set rTemp = B.Find(What:=WhatToFind, After:=Startt).Offset(-1, 0)
Set rfinal = Range(Startt, rTemp)
MsgBox rfinal.Address(0, 0)
End Sub
在这种情况下:
这里我们从 B5 开始,向下看,找到第一个" Net Amount" ..............然后备份一个细胞
答案 1 :(得分:0)
Range.Find
比迭代所有单元格更有效。
Dim rValue As Range, rNetAmount As Range, PRNG As Range
With Worksheets("Sales Orders").Cells
Set rValue = .Find(What:="Q300103176", After:=.Range("A1"), LookIn:=xlValues, LookAt:=xlWhole, SearchOrder:=xlByRows, SearchDirection:=xlNext, MatchCase:=False)
If Not rValue Is Nothing Then
Set rNetAmount = .Find(What:="Net Amount", After:=rValue, LookIn:=xlValues, LookAt:=xlWhole, SearchOrder:=xlByRows, SearchDirection:=xlNext, MatchCase:=False)
If Not rNetAmount Is Nothing Then
Set PRNG = .Range(rValue, rNetAmount.Offset(-1))
End If
End If
End With
答案 2 :(得分:0)
这就是我提出的:
Option Explicit
Public Function l_locate_last_value(Optional str_value As String = "Net Amount")
Dim my_cell As Range
Dim l_lowest As Long: l_lowest = -1
For Each my_cell In ActiveSheet.UsedRange
If my_cell = str_value And my_cell.Row > l_lowest Then
l_lowest = my_cell.Row
End If
Next my_cell
l_locate_last_value = l_lowest
End Function
稍后,您始终可以从结果中减去-1。 我正在使用UsedRange,因为它比迭代所有单元格更快(至少在我的PC上)。
答案 3 :(得分:0)
AutoFilter()
方法
Function GetRange(firstCell As Range, stringAfter As String) As Range
With Intersect(firstCell.EntireColumn, firstCell.Parent.UsedRange)
.AutoFilter Field:=1, Criteria1:=stringAfter
Set GetRange = .Parent.Range(firstCell, .Resize(.Rows.COUNT - 1).Offset(1).SpecialCells(xlCellTypeVisible).Areas(1).Cells(1, 1).Offset(-1))
.Parent.AutoFilterMode = False
End With
End Function
将在您的“主要”代码中使用,如:
Dim PRNG As Range
With ThisWorkbook.Worksheets("Sales Orders")
Set PRNG = GetRange(.Range("B5"), "Net Amount")
MsgBox PRNG.Address
'... other code
End With