我正在尝试编写一个函数,该函数返回与我在参数中给出的列相同的列上的特定单元格的值(lig =行号,col =列号),但每次运行它时,我收到错误'1004',这是我的代码:
Function week(lig As Integer, col As Integer) As Integer
Dim i As Integer
i = 0
Do Until Cells(lig - i, 1) = "Row labels"
i = i + 1
Loop
week = Cells(lig - i, col)
End Function
出现错误的行是:
Do Until Cells(lig - i, 1) = "Row labels"
我知道在测试包含整数的单元格的值之前,我会暂停类型错误,但我无法修复它。 有人可以帮忙吗?
答案 0 :(得分:1)
错误不是类型错误。问题是您正在尝试访问不存在的单元格。您的循环显然无法到达保存值“行标签”的单元格,并最终尝试访问单元格(0,1) - 这会触发错误1004.至于为什么会发生这种情况 - 您没有提供足够的详细信息说。
答案 1 :(得分:1)
我怀疑单元格中的值实际上是“行标签”或“行标签”或行标签“或其他实际上并不完全匹配的东西。试试这个:
Do Until Trim(Ucase(Cells(lig - i, 1))) = "ROW LABELS"
或者,如果您只是想在第一行停下来,请使用:
Do Until lig - i = 1
答案 2 :(得分:0)
i = 0将导致错误,因为工作表中不存在单元格(0,1)。如果从未找到逻辑,您可能还需要一个exit子句,因为当您点击工作表的末尾时会出现错误。如果你传递这个lig = 1你也会得到一个错误(因为lig -i(1-1)会导致0)所以你可能也想要处理那个场景
Function week(lig As Integer, col As Integer) As Integer
Dim i As Integer
i = 1'Changed to 1
Do Until Cells(lig - i, 1) = "Row labels"
i = i + 1
if i > 1000000 then exit do 'Exit clause
Loop
if i < 1000000 then
week = Cells(lig - i, col)
else
week = 0'Handle 0's in calling code
end if
End Function
答案 3 :(得分:0)
您可能会考虑重写如下,我认为更清楚。
Function week(lig As Integer, col As Integer) As Integer
Dim i As Integer
' Thsi function will return 0 if no row with the text is found
week = 0
For i = lig To 1 Step -1
If Cells(i, 1) = "Row labels" Then
week = Cells(i, col)
Exit For
End If
Next i
End Function
' EVEN BETTER USE THIS (or similar)!
Function week(MyCell As Range) As Integer
Dim i As Integer
week = 0
For i = MyCell.Row To 1 Step -1
If MyCell.Parent.Cells(i, 1) = "Row labels" Then
week = MyCell.Parent.Cells(i, MyCell.Column)
Exit For
End If
' Note
' MyCell.Parent. returns the sheet containing the cell
' Just using Cells(i, 1) (wihtout preceeding with "MyCell.Parent." will pick up
' cells on the currently active sheet, which may not be the sheet with the cell!
'
Next i
End Function