我正在尝试一个函数来获取2个值之间的序列。以下给出的示例为了更好地理解。
第一个值= A1245 第二个值= A1257
当我在'AddNum'函数中给出上面的值时。它应该给'A1245,A1246,A1247'作为结果。
下面给出了我自己写的vba代码,并请求你,请帮忙。
Public x As Double
Function AddNum(Val1 As Variant, Val2 As Variant)
If Val1 = "" Or Val2 = "" Then
Exit Function
Else
x = -(Right(Val1, 4) - Right(Val2, 4))
End If
Dim myary As Variant
ReDim myary(x) As Variant
For y = LBound(myary) To UBound(myary)
Z = Right(Val1, 4) + y
myary(y) = Left(Val1, 2) & Z
ActiveCell.Offset(0, y + 1).Value = myary(y)
Next y
End Function
答案 0 :(得分:0)
也许你是在追求这样的事情:
Sub AddNum(strng1 As Variant, strng2 As Variant)
Dim val1 As Long, val2 As Long
Dim code As String
Dim iVal As Long
If strng1 = "" Or strng1 = "" Then Exit Function
code = Left(strng1, 1)
val1 = CLng(Right(strng1, 4))
val2 = CLng(Right(strng2, 4))
ReDim myary(1 To val2 - val1 + 1) As String
For iVal = val1 To val2
myary(iVal - val1 + 1) = code & iVal
Next iVal
ActiveCell.Offset(, 1).Resize(, UBound(myary)).Value = myary
End Sub
或者你可以利用Autofill()
方法:
Sub AddNum2(strng1 As Variant, strng2 As Variant)
Dim val1 As Long, val2 As Long
Dim iVal As Long
Dim code As String
If strng1 = "" Or strng1 = "" Then Exit Sub
code = Left(strng1, 1)
val1 = CLng(Right(strng1, 4))
val2 = CLng(Right(strng2, 4))
With ActiveCell.Resize(, 2)
.Value = Array(strng1, code & (val1 + 1))
.AutoFill Destination:=.Resize(, val2 - val1 + 1), Type:=xlFillDefault
End With
End Sub
答案 1 :(得分:0)
我不确定这是否是您的帖子的意图,但如果您想将结果放在1 Cell(调用此Function
的单元格)中,那么您需要定义此函数以返回{ {1}}。
此外,代码假设您将在字符串的开头只作为一个字母(作为前缀)调用它,如果您想要具有多功能性,在开头用各种字母调用此函数,那么您将需要在调用部分添加另一个参数。
<强>代码强>
String