Excel根据源的长度获取值

时间:2015-06-29 11:17:00

标签: excel vba excel-vba

目前我们有一小段代码可以获取单元格的值并返回4位数字。

例如L12341234D12341234

但是现在我们的值为5位L12345,例如它们只是作为最后2位返回。例如L12345正在返回45

我想要的是修改代码以允许4位和5位变体。

当前代码:

  If GetElm(Range("F" & i).value, 3) = "8260" Then
    CodeD = GetElm(Range("F" & i).value, 4)
  End If
  col9 = Right(CodeD, 4)

返回:

Input   Output
L1234   1234
L12345  45

我尝试过:

  If GetElm(Range("F" & i).value, 3) = "8260" Then
    CodeD = GetElm(Range("F" & i).value, 4)
  ElseIf GetElm(Range("F" & i).value, 3) = "8260" Then
    CodeD = GetElm(Range("F" & i).value, 5)
  End If
  col9 = Right(CodeD, 5)

返回:

Input   Output
L1234   L1234
L12345  12345

这会正确返回5位数字,但正在返回4位数字。

编辑:

GetElm定义:

Function GetElm(value As String, elmno As Integer)

If elmno = 1 Then
  GetElm = Left(value, 1)
ElseIf elmno = 2 Then
  GetElm = Mid(value, 3, 3)
ElseIf elmno = 3 Then
  GetElm = Mid(value, 7, 4)
ElseIf elmno = 4 Then
  GetElm = Mid(value, 12, 8)
End If

End Function

3 个答案:

答案 0 :(得分:1)

如果您只想跳过第一个字符,可以使用:

col9 = Mid(CodeD, 2)

答案 1 :(得分:1)

如果你想要做的就是跳过单元格值中的第一个字符,那么:

Function GetElm (byval value as string) as string
   GetElm = Right(value, Len(value)-1)
End Function

应该这样做。

这假设您始终使用1个字母的n位代码。

但是,我不理解你的GetElm函数定义中第二个参数的使用。

此致 路易斯

答案 2 :(得分:0)

增加了功能:

Function onlyDigits(s As String) As String
    ' Variables needed (remember to use "option explicit").   '
    Dim retval As String    ' This is the return string.      '
    Dim i As Integer        ' Counter for character position. '

    ' Initialise return string to empty                       '
    retval = ""

    ' For every character in input string, copy digits to     '
    '   return string.                                        '
    For i = 1 To Len(s)
        If Mid(s, i, 1) >= "0" And Mid(s, i, 1) <= "9" Then
            retval = retval + Mid(s, i, 1)
        End If
    Next

    ' Then return the return string.                          '
    onlyDigits = retval
End Function

然后使用代码:

  If GetElm(Range("F" & i).value, 3) = "8260" Then
    CodeD = GetElm(Range("F" & i).value, 4)
  End If
  col9 = onlyDigits(CodeD)