添加0,其中字符串末尾只有两个字符

时间:2015-08-25 15:21:05

标签: excel vba

我正在寻找一个excel宏来查看一列数据并添加一个0,其中字符串末尾只有2个数字。

AAA / 97

将成为

AAA / 097。

在原始工作表中,会有一个正确的条目混合,如上面的那个和错误的条目,如上面的例子

我理解公式可能会更容易,但这是一个广泛的列表,所以我觉得宏更适合。

感谢任何帮助。

4 个答案:

答案 0 :(得分:0)

不要使用VBA,因为不是每个人都喜欢打开包含宏的工作簿。改为使用公式:

如果A1包含单元格,则

=IF(LEN(A1)=6,LEFT(A1,4)&"0"&RIGHT(A1,2),A1)

向下复制。这对于“正确”的细胞来说是良性的。

答案 1 :(得分:0)

尝试:

=IF(LEN(MID(A1,FIND("/",A1,1)+1,3))<3,(MID(A1,1,FIND("/",A1,1)))&"0"&(MID(A1,FIND("/",A1,1)+1,3)),LEN(MID(A1,FIND("/",A1,1)+1,3)))

答案 2 :(得分:0)

您需要添加一些错误检查,但这些是基础

Public Sub MakeZero()

    Dim rCell As Range
    Dim vaSplit As Variant

    Const sDELIM As String = "/"

    For Each rCell In Sheet1.Range("A1:A100").Cells
        vaSplit = Split(rCell.Value, sDELIM)
        rCell.Value = vaSplit(0) & sDELIM & Format(Val(vaSplit(1)), "000")
    Next rCell

End Sub

答案 3 :(得分:0)

以下是一些可以解决问题的代码。我原以为你不会把$视为数字。

Sub AddZero()
Dim wb As Workbook, ws As Worksheet, rng As Range
Dim chkBool As Boolean, char3 As String, char2 As String, char1 As String
Set wb = ThisWorkbook 'change this to suit your workbook
Set ws = wb.Worksheets("Sheet1") 'change this to suit your sheet
Set rng = ws.Range("B:B") 'change this to suit your range
For Each Cell In rng
    If IsEmpty(Cell.Value) Then
        Set rng = Nothing
        Set ws = Nothing
        Set wb = Nothing
        Exit Sub 'I have assumed that there will not be blank rows in the range
    End If
    '''''' start checking the numbers at the end of the string
    char3 = Mid(Cell.Value, Len(Cell.Value), 1)
    char2 = Mid(Cell.Value, Len(Cell.Value) - 1, 1)
    char1 = Mid(Cell.Value, Len(Cell.Value) - 2, 1)
    If IsNumeric(char3) And char3 <> "$" Then 'isnumeric check the next character
        If IsNumeric(char2) And char2 <> "$" Then
            If IsNumeric(char1) And char1 <> "$" Then
                chkBool = True
            End If
            If chkBool = False Then
                Cell.Value = Mid(Cell.Value, 1, Len(Cell.Value) - 2) & "0" & char2 & char3 'reform the cell value
            End If
            chkBool = False 'reset the check if there is already 3 numbers at the end of the string
        Else:
            Cell.Value = Mid(Cell.Value, 1, Len(Cell.Value) - 1) & "00" & char3
        End If
    Else:
        'Cell.Value = Mid(Cell.Value, 1, Len(Cell.Value) - 2) & "000" 'not sure if you need this but if no numbers found will mask the end with 000
    End If
Next Cell
Set rng = Nothing
Set ws = Nothing
Set wb = Nothing
End Sub

我认为Dick的答案最好是你可以使用分隔符,如果你的分隔符并不总是存在或者不同,那么我的工作会更好,这取决于你的情况。