【发布时间】:2020-10-28 22:13:40
【问题描述】:
我正在尝试寻找值来为票证核对过程创建最终票证号。这是应该发生的:
子程序在单元格“Gx”中查找值
- 如果它找到一个值
- 将值传递给函数以去除字母,转换为数字,传回子程序以放入 单元格“Ax”
- 如果没有值
- 将“Cx”的值传递给函数等
这会根据填充在单独列中的行数循环遍历我在工作表中的单元格。
该函数本身在工作表中工作正常,但是当我从子例程列中传递一个值时,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
我错过了什么?
【问题讨论】:
-
您的函数永远不会将传递的字符串转换为范围。您需要将其包装在
range中。事实上,最好通过一个范围。 -
谢谢你,成功了。简单的修复,我不敢相信我没有看到。
标签: vba function subroutine