How to call a custom function in VBA

1. Questions raised

In VBA, I want to judge the values ​​of all non-empty cells in column B. If it is greater than 60, write "pass" in the cell next to it, otherwise write fail. As shown below:

 

 Since the number of non-empty cells in column B cannot be determined, we need to define a custom function to obtain the value of the last non-empty cell in column B, and then perform a traversal loop. In order to make the program clearer, I decided to define a function in advance, and then call the return value of the custom function in the main program.

2. Problem solving

1. Set custom function

In VBA, we insert a module and write a custom function

Function lastRow(col As Range) As Long
    lastRow = col.Cells(col.Cells.Count).End(xlUp).Row
End Function

Here, lastRow is the function name, and col as Range in parentheses refers to the parameter name and type.

When calling this function, we can use the function name (parameter), such as lastRow(Range(B:B))

In VBA, End(xlUp) is a method for locating cells, which can be used to find the position of the last non-empty cell in a certain column or row.

The function of End(xlUp) is to search upwards from the current cell until the first non-empty cell is encountered. What it returns is a Range object, which represents the location of the searched cell.

When using the End(xlUp) method, you usually need to specify the starting cell first, and then use the End(xlUp) method to find the position of the last non-empty cell. For example, the following code finds the position of the last non-empty cell in column A:

lastRow = Range("A1").End(xlDown).Row

2. Write the main program

Sub 逻辑判断()

Dim last As Long

last = lastRow(Range("B:B")) '直接获取函数的返回值。
 
For i = 1 To last
    If Range("b" & i) < 60 Then
        Range("c" & i).Value = "不及格"
    Else
        Range("c" & i).Value = "及格"  
    End If
Next i
End Sub

3. Post-school reflection

  1. The above problem is solved by using a custom function, or by judging whether the current cell is empty, and then executing the main program.
  2. In this case, important knowledge points such as for loop, if judgment, and custom function call are used. If you can understand it deeply, you can further deepen your understanding of VBA programming.
  3. It should be noted that the custom functions and the main program can be executed sequentially only if they are placed under the same module.

Guess you like

Origin blog.csdn.net/henanlion/article/details/131041694