2016-11-24 46 views
-1

我正在尝试获取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

我不明白你在等待什么。是VAL1/VAL2字符串?或范围?结果你想要一个字符串?范围?什么是规则? “你给A1257,但它会返回到A1247”..请解释你期望的功能 –

+0

@Sai Krishna你是否尝试过下面提供的任何解决方案?他们是否按照你的意图工作? –

回答

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 
+0

@SaiKrishna,你通过了吗? – user3598756

0

我不知道如果这是你的文章的意图,但是如果你想在1 Cell(称为Function的单元)内获得结果,那么你需要定义这个函数返回String

此外,该代码假定您将在字符串的开头(作为前缀)中只用1个字母来调用它,如果您希望具有通用性,可以在开始时用各种字母调用此函数,那么您将需要添加另一个参数到调用部分。

代码

Function AddNum(Val1 As Variant, Val2 As Variant) As String 

Dim MinVal, MaxVal 
Dim i As Long 
Dim CellStr As String, Prefix As String 

If Val1 = "" Or Val2 = "" Then 
    Exit Function 
Else 
    ' get the first letter on the left >> modify if you have more than 1 letter 
    Prefix = Left(Val1, 1) 

    ' read the "clean" value without the prefix and convert to Long 
    MinVal = CLng(Mid(Val1, 2, Len(Val1) - 1)) 
    MaxVal = CLng(Mid(Val2, 2, Len(Val2) - 1)) 
End If 

For i = MinVal To MaxVal 
    If CellStr = "" Then 
     CellStr = Prefix & i 
    Else 
     CellStr = CellStr & "," & Prefix & i 
    End If 
Next i 
AddNum = CellStr 

End Function