VBA,寻找细胞地址,并用作另一个发现的范围

我目前正在试图弄清楚发生了什么事情,我试图在VBA中使用两个独立的search函数来查找一系列单元格的开始和结束,然后将其设置为另一个search的范围。 这可能是一个非常简单的东西,但我不能为了我的生活弄清楚,我已经包含了我现在的代码。

Truecheck是一个全局variables,用于存储要在spreadhseet中search的名称。 我想要定义的范围的开始和结束将具有相同的名称,所以truecheck应该适用于这两个。

有没有人有任何想法如何使这项工作?

此刻它抛出一个对象所需的错误,突出显示我设置“Firstrow = Range ….”的部分。 但是我也认为这里有不止一个问题

编辑:Potatoes.value和Textboxinput.value是用户窗体上的文本框

Private Sub optionselect() Dim LastLocation As String Dim FirstLocation As String Dim FirstRow As Long Dim LastRow As Long Dim SearchVal As String FirstLocation = Range("B:B").Find(truecheck,_ LookIn:=xlValues,LookAt:=xlWhole, SearchOrder:=xlByRows) LastLocation = Range("B:B").Find(truecheck, LookIn:=xlValues,_ LookAt:=xlWhole, SearchOrder:=xlByRows, searchdirection:=xlPrevious) FirstRow = Range(FirstLocation).Row LastRow = Range(LastLocation).Row Potatoes.Value = Application.WorksheetFunction.VLookup(LengthInputText.Value,_ Range(Cells(FirstRow, 8), Cells(LastRow, 8)), 6, False) End Sub 

FirstLocationLastLocation are both defined asstring, yet you are assigning them to a object in the way the statement is written, as the yet you are assigning them to a Range object in the way the statement is written, as the Find method returns the cell (orfindmethod returns the cell (or Range对象)。

最简单的方法是将Address属性添加到调用中。

 FirstLocation = Range("B:B").Find(truecheck,_ LookIn:=xlValues,LookAt:=xlWhole, SearchOrder:=xlByRows).Address LastLocation = Range("B:B").Find(truecheck, LookIn:=xlValues,_ LookAt:=xlWhole, SearchOrder:=xlByRows, searchdirection:=xlPrevious).Address 

不过,这也可以做到:

 Dim FirstLocation as Range, LastLocation as Range Set FirstLocation = Range("B:B").Find(truecheck,_ LookIn:=xlValues,LookAt:=xlWhole, SearchOrder:=xlByRows) Set LastLocation = Range("B:B").Find(truecheck, LookIn:=xlValues,_ LookAt:=xlWhole, SearchOrder:=xlByRows, searchdirection:=xlPrevious) FirstRow = FirstLocation.Row LastRow = LastLocation.Row 

它看起来像Range.Find的返回types是一个范围而不是一个string。 改变你的代码看起来像这样并尝试:

 Private Sub optionselect() Dim LastLocation As Range Dim FirstLocation As Range Dim FirstRow As Long Dim LastRow As Long Dim SearchVal As String Set FirstLocation = Range("B:B").Find("It", LookIn:=xlValues, LookAt:=xlWhole, SearchOrder:=xlByRows) Set LastLocation = Range("B:B").Find(truecheck, LookIn:=xlValues, LookAt:=xlWhole, SearchOrder:=xlByRows, searchdirection:=xlPrevious) FirstRow = FirstLocation.Row LastRow = LastLocation.Row Potatoes.Value = Application.WorksheetFunction.VLookup(LengthInputText.Value,_ Range(Cells(FirstRow, 8), Cells(LastRow, 8)), 6, False) End Sub 

仅供参考: https : //msdn.microsoft.com/en-us/library/office/ff839746.aspx