这是我的问题。我希望我的函数返回一个单元格对象,该对象可以视为数据开始,具体取决于您查看字符串的一部分还是整个单词。
Function lookForDataStart(sht, word, searchtype as Variant)
Set wordLocation = sht.Range("A1:D150").Find(word, LookAt:=searchtype)
If Not (wordLocation Is Nothing) Then
c = wordLocation.Column
r = wordLocation.Row
r = r + 1
Do Until sht.Cells(r, c) <> ""
r = r + 1
Loop
Set lookForDataStart = sht.Cells(r, c)
Else
Set lookForDataStart = Nothing
End If
End Function
根据文档,存在xlPart或xlWhole参数,它们是Variant类型。当我尝试使用我的功能时,例如设置startCell = lookForDataStart(wks, sectionName, xlPart)
,我收到searchtype
下值为空的“下标超出范围”错误。怎么了?
答案 0 :(得分:0)
基于问题详细信息的工作代码。
Sub Test2()
Dim startCell As Range
Dim sht As Worksheet
Set sht = Worksheets("Sheet1")
Dim word As String
word = "Test"
Dim searchtype As Variant
searchtype = "xlPart" 'xlWhole
Set startCell = lookForDataStart(sht, word, xlPart)
MsgBox startCell
End Sub
Function lookForDataStart(sht As Worksheet, word As String, searchtype As Variant)
Set wordLocation = sht.Range("A1:D150").Find(word, LookAt:=searchtype)
If Not (wordLocation Is Nothing) Then
c = wordLocation.Column
r = wordLocation.Row
r = r + 1
Do Until sht.Cells(r, c) <> ""
r = r + 1
Loop
Set lookForDataStart = sht.Cells(r, c)
Else
Set lookForDataStart = Nothing
End If
End Function