在VBA中调用Sub时出错

时间:2017-07-27 13:26:04

标签: excel vba excel-vba

我在调用sub时面临问题。错误消息是错误的参数数量或无效的属性赋值。我尝试了很多变化,没有任何效果。

Sub last_non_empty_cell_in_a_row()

Dim rngCell As Range, i As Long

Set rngCell = Cells.Find(What:="*", After:=Cells(1, 1), LookIn:=xlFormulas, 
LookAt _
:=xlPart, SearchOrder:=xlByRows, SearchDirection:=xlPrevious, MatchCase:= _
False, SearchFormat:=False) '.Activate
i = rngCell.Row

End Sub


Sub code_main()

Dim x As Long

Call last_non_empty_cell_in_a_row(i)

For x = 1 To i
If Range("R" & x) = "m_M" Then
If Range("P" & x) = "m_DH" Then
If Range("Q" & x) = "" Then
Else
Range("P" & x, "R" & x).Interior.ColorIndex = 22
End If
Else
Range("P" & x, "R" & x).Interior.ColorIndex = 22
End If
Else
Range("P" & x, "R" & x).Interior.ColorIndex = 0

End If

Next x



End Sub

1 个答案:

答案 0 :(得分:2)

您希望将last_non_empty_cell_in_a_row更改为Function并让返回 i的值。

Function last_non_empty_cell_in_a_row() As Long

Dim rngCell As Range, i As Long
Set rngCell = Cells.Find(What:="*", After:=Cells(1, 1), LookIn:=xlFormulas, 
LookAt _
:=xlPart, SearchOrder:=xlByRows, SearchDirection:=xlPrevious, MatchCase:= _
False, SearchFormat:=False) '.Activate
i = rngCell.Row
last_non_empty_cell_in_a_row = i
End Function

然后,在调用程序中:

Sub code_main()

Dim x As Long

For x = 1 to last_non_empty_cell_in_a_row()
...

可能还有其他问题或错误,我没有测试过。值得注意的是,last_non_empty_cell_in_a_row似乎是一个函数签名,它并没有真正描述函数返回的内容。有关获取给定范围或工作表中“最后一个单元格”的方法,请参阅:

Error in finding last used cell in VBA