如何将参数从子例程传递到 VBA 中的函数?

How do I pass an argument from a subroutine to a function in VBA?

我正在尝试寻找值来为工单核对流程创建最终工单编号。这是应该发生的事情:

子例程在单元格“Gx”中查找值

这会根据单独列中填充的行数循环遍历我工作表中的数字单元格。

该函数在工作表中本身运行良好,但当我将子例程 A 列中的值传递给它时,该值会填满行号,即。 A37=37,A8=8。我认为我没有将参数正确传递给函数,但我不确定。这是子例程和函数的代码:

    Sub final_ticket_number()
    Dim rw As Integer
    Dim i As Integer

    'header label
    Range("A1").Value = "Final Ticket #"

    'set number of rows for loop
    With Worksheets(1)
        rw = .Range("B2").End(xlDown).Row
    End With

    'check col G for empty, use col C as backup
    For i = 2 To rw
        If Not IsEmpty(Cells(i, "G")) Then
            'strip out letters in col G, place in col A
            Cells(i, "A").Value = getNumeric("G" & i)
        Else
            'strip out letters in col C, place in col A
            Cells(i, "A").Value = getNumeric("C" & i)
        End If
    Next i
    
    End Sub

    Function getNumeric(cellRef As String) As Long 'remove letters from ticket numbers
    Dim stringLength As Integer
    Dim i As Byte
    Dim Result As String
    stringLength = Len(cellRef)

    'loops through each character in a cell to evaluate if number or not
    For i = 1 To stringLength
        If IsNumeric(Mid(cellRef, i, 1)) Then
            Result = Result & Mid(cellRef, i, 1)
        End If
    Next i

    'convert remaining characters to number
    getNumeric = CLng(Result)

    End Function

我错过了什么?

据我了解,唯一错误的是你的Len(cellRef),这里你只是传递了范围而不是他的值。看看我是怎么做到的,我必须指定电子表格,做同样的工作。

使用debug.print查看变量的输出。写入代码“debug.print XvariableX”并在立即检查 (Ctrl + G) 中看到分配给变量的值。祝你好运。

Sub final_ticket_number()
Dim rw As Integer
Dim i As Integer

Range("A1").Value = "Final Ticket #"

With Worksheets(1)
    rw = .Range("B2").End(xlDown).Row
End With

For i = 2 To rw
    If Not IsEmpty(Cells(i, "G")) Then
        Cells(i, "A").Value = getNumeric("G" & i)
    Else
        Cells(i, "A").Value = getNumeric("C" & i)
    End If
Next i
End Sub

Function getNumeric(cellRef As String) As Long 'remove letters from ticket numbers
Dim stringLength As Integer
Dim i As Byte
Dim Result As String

Dim Wrs As String
Wrk = ActiveWorkbook.Name
Workbooks(Wrk).Activate
Wrs = ActiveSheet.Name
stringLength = Len(Workbooks(Wrk).Worksheets(Wrs).Range(cellRef))

For i = 1 To stringLength
    If IsNumeric(Mid(Workbooks(Wrk).Worksheets(Wrs).Range(cellRef), i, 1)) Then
        Result = Result & Mid(Workbooks(Wrk).Worksheets(Wrs).Range(cellRef), i, 1)
    End If
Next i

getNumeric = CLng(Result)
End Function