VBA Excel将Main Sub中的值链接到其调用的函数

我在excel中对vba还是很新的东西,并且正面临着解决这个问题的困难。我真的很希望有人能够启发我,我的代码出了什么问题,并为我提供了尽可能简化的解决scheme。 非常感谢,真的很感激!

问题:贷款申请根据客户的收入进行评估。 我们应该使用For-Next函数和IF语句来显示以下批准状态:

客户的收入与各自的地位

60,000以特殊费率批准; > 40,000标准费率批准; > 24,000等待经理的批准; 其他情况拒绝申请

从Excel中的第2行开始,B列包含“客户收入”数字,Excel中的C列包含“贷款申请状态”数字。

我的代码运行良好,如下所示:

Sub ForNext_If() 'CINCOME = Customer Income,Loan status= the application status, x = the row number, FinalRow= last row number x = 2 For x = 2 To 11 Step 1 CINCOME = Cells(x, 2).Value If CINCOME > 60000 Then LOANSTATUS = "Approve with special rates" ElseIf CINCOME > 40000 Then LOANSTATUS = "Approve with standard rates" ElseIf CINCOME > 24000 Then LOANSTATUS = "Await manager's approval" Else LOANSTATUS = "Reject application" End If Cells(x, 4) = LOANSTATUS Next End Sub 

但是,当我尝试使用通话function时,

 Sub ForNext_If() x = 2 For x = 2 To 11 Step 1 CINCOME = Cells(x, 2).Value Call Calling Cells(x, 4) = LOANSTATUS Next End Sub Function Calling() If CINCOME > 60000 Then LOANSTATUS = "Approve with special rates" ElseIf CINCOME > 40000 Then LOANSTATUS = "Approve with standard rates" ElseIf CINCOME > 24000 Then LOANSTATUS = "Await manager's approval" Else LOANSTATUS = "Reject application" End If End Function 

CINCOME的价值似乎无法转移到“调用”函数,以确定贷款申请状态.T_T究竟出了什么问题?

继续评论。 我已经为你准备了两个解决scheme(还有更多,但是这两个是我头上的第一个解决scheme)。


  1. 用户自定义函数
    一旦这个函数被粘贴到你的任何模块中,你可以通过点击单元格并写入= LoanAppStatus(range),即= LoanAppStatus(B2)+来使用它,然后你可以在列中拖动它

     ' User Defined Function ' Returns the status of customers loan application based on the income Function LoanAppStatus(CINCOME As Range) As String If CINCOME.Value >= 24000 And CINCOME.Value < 40000 Then LoanAppStatus = "Await manager's approval" ElseIf CINCOME.Value >= 40000 And CINCOME.Value < 60000 Then LoanAppStatus = "Approve with standard rates" ElseIf CINCOME.Value > 60000 Then LoanAppStatus = "Approve with special rates" Else LoanAppStatus = "Reject application" End If 

    结束function

2.重写你原来的子程序

 'Procedure ' Fills the status of customers loan application (Column C) based on the income ( Column B ) Sub ForNext_If() Dim i As Long Dim wS As Worksheet Set wS = ThisWorkbook.ActiveSheet ' Range("B" & i).Value its what you called CINCOME ' Range("C" & i).Value its what you called LOANSTATUS With wS For i = 2 To Range("B" & Rows.Count).End(xlUp).Row If Range("B" & i).Value > 60000 Then Range("C" & i).Value = "Approve with special rates" ElseIf Range("B" & i).Value >= 40000 And Range("B" & i).Value < 60000 Then Range("C" & i).Value = "Approve with standard rates" ElseIf Range("B" & i).Value >= 24000 And Range("B" & i).Value < 40000 Then Range("C" & i).Value = "Await manager's approval" Else Range("C" & i).Value = "Reject application" End If Next i End With End Sub