增加包含数字和文本VBA的单元格值

时间:2017-09-22 12:27:41

标签: excel vba

我已经尝试过这个代码,它适用于只包含数字的单元格:

Sub IncreaseCellValue()
    'Add 1 to the existing cell value
    Range("A1").Value = Range("A1") + 1
End Sub

如果单元格包含文本和数字,我该怎么做类似的事情。例如,我有" Apple 1"我希望"增加"细胞文本到" Apple 2"下次我运行宏,我想要" Apple 3"。

4 个答案:

答案 0 :(得分:3)

以下是解决此问题的另一种方法:

Sub IncreaseCellValue()
    Dim value As Variant

    'Add 1 to the existing cell value

    If IsNumeric(Range("A1").value) Then
       Range("A1").value = Range("A1") + 1
    Else
       value = Split(Range("A1").value, " ")
       Range("A1").value = value(0) & " " & (CInt(value(1)) + 1)
    End If
End Sub

它将涵盖您在问题中提出的2个案例,但不包括您可以提出的每个案例。

答案 1 :(得分:0)

尝试使用以下功能

Sub IncreaseCellValue()
    'Add 1 to the existing cell value
    Range("A1").Value = Replace(Range("A1").Value2, CleanString(Range("A1")), vbNullString) & CInt(CleanString(Range("A1").Value2)) + 1
End Sub
Function CleanString(strIn As String) As String
    Dim objRegex
    Set objRegex = CreateObject("vbscript.regexp")
    With objRegex
     .Global = True
     .Pattern = "[^\d]+"
    CleanString = .Replace(strIn, vbNullString)
    End With
End Function

答案 2 :(得分:0)

请检查:

Option Explicit


Sub IncreaseCellValue()
    'Add 1 to the existing cell value

    Dim rg As Range

    Set rg = Cells(Rows.Count, "A").End(xlUp)



  Range("A1" & ":" & rg.Address).AutoFill Destination:=Range("A1" & ":" & rg.Offset(1, 0).Address), Type:=xlFillDefault

End Sub

答案 3 :(得分:0)

或者您可以尝试这样的事情......

Function GetNumber(ByVal rng As Range) As Long
Dim i As Long
For i = Len(rng.Value) To 1 Step -1
    If IsNumeric(Mid(rng.Value, i, 1)) Then
        GetNumber = GetNumber & Mid(rng.Value, i, 1)
    Else
        Exit For
    End If
Next i
End Function

Sub IncrementNumber()
Dim num As Long
num = GetNumber(Range("A1"))
Range("A1").Value = Replace(Range("A1").Value, num, num + 1)
End Sub