我正在试图弄清楚我的头发是怎么回事, 我试图在VBA中使用两个单独的搜索功能来查找一系列单元格的开始和结束,然后将其设置为另一个搜索的范围。这可能是非常简单的事情,但我不能为我的生活弄清楚,我已经包含了我目前的代码。
Truecheck是一个全局变量,用于存储spreadhseet中要搜索的名称。我想要定义的范围的开始和结束将具有相同的名称,因此truecheck应该适用于两者。
有人有任何想法如何使这项工作?
此刻它正在抛出一个物体所需的错误,突出显示我设置“Firstrow = Range ....”的部分。我也认为这里存在不止一个问题
编辑:Potatoes.value和Textboxinput.value是userform
上的文本框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
答案 0 :(得分:1)
FirstLocation
和LastLocation are both defined as
字符串yet you are assigning them to a
范围object in the way the statement is written, as the
查找method returns the cell (or
范围`对象)找到的单元格。
实现此功能的最简单方法是将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
答案 1 :(得分:0)
看起来Range.Find的返回类型是一个范围而不是字符串。将代码更改为如下所示并尝试:
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