因为您说字母/数字组合的数量比您的示例中的要多得多,所以我认为这是 VBA 的问题,而不是工作表函数。一个 WS 功能将变得难以维护并且非常迅速。
我做了这4个功能。该GetCharArray
函数解析您传递给它的字符串的文本,以将该文本作为字符数组返回(即使 BA 没有char
类型只是一个string
类型,所以我返回一个字符串。同样的想法)
然后假设我们可以调用GetNumberFromChars
以获取50
fromVL50s
并调用GetLeftMostLetters
以获取VL
from VL50s
。
然后是一些工作表,我创建了一个命名范围keys
,其中范围的第 1 列是字母,如“VL”、“H”、“M”......并且与之关联的相应值在第 2 列中。它看起来像
Col1 Col2
VL 1
M 2
H 3
... ...
我们可以使用带有和结果的vlookup
工作表函数来找到应该添加到结果中的数字。Range("keys")
GetLeftMostLetters
GetNumberFromChars
Function GetNewNumber(inString As String) As Double
Dim searchString As String, numberToAddFromKeys As Double, numberToAddToFromCell As Long, cellChars() As String
cellChars = GetCharArray(inString)
searchString = GetLeftMostLetters(cellChars)
numberToAddToFromCell = GetNumberFromChars(cellChars)
'use the keys named range where column 1 is your letters ("VL","H"...)
'and column 2 is the corresponding value for that letter set
numberToAddFromKeys = WorksheetFunction.VLookup(searchString, Range("keys"), 2, 0)
GetNewNumber = CDbl(numberToAddFromKeys) + CDbl(numberToAddToFromCell)
End Function
Function GetNumberFromChars(inChars() As String) As Long
Dim returnNumber As String, i As Long, numberStarted As Boolean
For i = 1 To UBound(inChars)
If IsNumeric(inChars(i)) Then
If Not numberStarted Then numberStarted = True
returnNumber = returnNumber & inChars(i)
Else
If numberStarted Then
'this will ignore that "s" on the end of your sample data
'hopefully that's what you need
GetNumberFromChars = returnNumber
Exit Function
End If
End If
Next
End Function
Function GetLeftMostLetters(inChars() As String) As String
Dim returnString As String, i As Long
For i = 1 To UBound(inChars)
If Not IsNumeric(inChars(i)) Then
returnString = returnString & inChars(i)
Else
GetLeftMostLetters = returnString
End If
Next
End Function
Function GetCharArray(inText As String) As String()
Dim s() As String, i As Long
ReDim s(1 To Len(inText))
For i = 1 To UBound(s)
s(i) = Mid$(inText, i, 1)
Next
GetCharArray = s
End Function
所以可以这样使用...
Dim cell As Range, rng As Range
'set this range to your actual range.
Set rng = Sheets("your sheet name").Range("A1:A5")
For Each cell In rng
'put this resulting value wherever you want.
Debug.Print GetNewNumber(cell.Value)
Next cell