我是Visual Basic的新手,遇到了一些麻烦。我收到了错误,
对象变量或未设置块变量
在For Each r In Sheet1.Cells.CurrentRegion.Find(s)
看起来我没有正确设置指针,但我不知道该怎么做。我确定还有其他一些错误,所以任何想法或评论都是最受欢迎的。
代码是在工作表中的某处找到特定字符串,并计算该行的总发票金额的百分比。检查以确保该行不属于同一发票,在这种情况下使用相同的总额。
Public charges(2) As String
Public r As Range
Public s As Variant
Public difference As Integer
Sub Script()
Range("M1").Value = "Apportioned Rate"
charges(0) = "Standard Rebuild Valuation"
charges(1) = "billable charge"
For Each s In charges
For Each r In Sheet1.Cells.CurrentRegion.Find(s) //where exception occurs
Select Case r.Offset(0, -4).Value
Case Is <> r.Offset(-1, -4).Value
Calculate difference = 0, r
Case Is = r.Offset(-10, -4).Value
Calculate difference = -10, r
Case Is = r.Offset(-9, -4).Value
Calculate difference = -9, r
Case Is = r.Offset(-8, -4).Value
Calculate difference = -8, r
Case Is = r.Offset(-7, -4).Value
Calculate difference = -7, r
Case Is = r.Offset(-6, -4).Value
Calculate difference = -6, r
Case Is = r.Offset(-5, -4).Value
Calculate difference = -5, r
Case Is = r.Offset(-4, -4).Value
Calculate difference = -4, r
Case Is = r.Offset(-3, -4).Value
Calculate difference = -3, r
Case Is = r.Offset(-2, -4).Value
Calculate difference = -2, r
Case Is = r.Offset(-1, -4).Value
Calculate difference = -1, r
End Select
Next r
Next s
End Sub
Public Function Calculate(ByVal difference As Integer, r As Range) As Variant
Select Case r.Value
Case Is = charges(0)
r.Offset(difference, 6).Value = r.Offset(difference, 5).Value * 0.5
Case Is = charges(1)
r.Offset(difference, 6).Value = r.Offset(difference, 5).Value * 0.25
End Select
End Function
答案 0 :(得分:2)
我可以看到错误的原因有两个。
Sheet1.Cells.CurrentRegion
实际上并未选择您要搜索的区域Nothing
,这是.Find()
函数返回的内容,如果找不到任何内容。按此顺序检查这些内容并查看问题所在。
编辑: 你应该首先测试它是否找到了什么,如:
Dim rng as Range
set rng = Sheet1.Cells.CurrentRegion.Find(s)
If rng is nothing then
' "nothing" handling
Else
' your main search code
End if
另外,正如Ron Rosenfeld和其他人在评论中所说,.Find()只返回第一个结果,你需要通过.FindNext()
来迭代另一个结果。答案 1 :(得分:0)
Sheet1.Cells.CurrentRegion未选择您期望的区域的原因是CurrentRegion选择由空行和空白列的任意组合限定的范围。
因此,Sheet1.Cells基本上选择了工作表中所有单元格的范围,活动单元格为A1。现在,如果B列是空白而第2行也是空白,那么您最终选择了Range(&#34; A1&#34;)。
您可以使用快捷键Ctrl + *。
在Excel中测试CurrentRegion的行为如果你跳过CurrentRegion,你的代码是有效的,即:
For Each r In Sheet1.Cells.Find(s)