【问题标题】:Parse strings, and add a number to the value解析字符串,并在值中添加一个数字
【发布时间】:2012-03-06 20:29:44
【问题描述】:

我有一个 Excel 表格,其中有时整个单元格包含以下内容:

pos=51;70;112;111;132;153

注意单个单元格中的全部内容,也就是说值51;70;112... 是在单个单元格中聚集在一起的字符串,而不是在它们自己的单元格中。

我可以编写一个宏,在所有包含关键字"pos=" 的单元格中,将每个值加 2,这样最终的结果是:

pos=53;72;114;113;134;155

【问题讨论】:

  • 总是 5 个分号还是也不同?
  • @rene: 其实没关系

标签: string vba excel delimiter


【解决方案1】:

这是一个可以做到这一点的代码(在我的 Excel 2003 上的一个示例上进行了测试):

Sub t()
Dim rCells As Range, c As Range
Dim arr As Variant, i As Integer

'Define the range to apply the code
Set rCells = Range("A1")
For Each c In rCells
    'check if the cell desserves to be changed (could be adapted though to another check)
    If Left(c.Value, 4) = "pos=" Then
        'split all the values after the "pos=" into an array
        arr = Split(Mid(c.Value, 5, Len(c.Value)), ";")
        'add +2 to every value of the array (we convert the value to be sure, probably unneeded)
        For i = 0 To UBound(arr)
            arr(i) = CLng(arr(i)) + 2
        Next i
        'set back the value to the worksheet
        c.Value = "pos=" & Join(arr, ";")
    End If
Next c
End Sub

请注意,如果您的值格式不正确,我没有添加错误检查部分。

【讨论】:

    【解决方案2】:

    您知道无需使用宏即可轻松拆分数据,对吧?只需使用“数据”选项卡上的 TextToColumns 函数

    但如果你真的想要一个宏,你可以这样做:

    Sub AddNumber()
        Dim numberToAdd As Integer
        numberToAdd = 2
    
        Set myRange = Range("A1:A5")
        For Each myCell In myRange
        If Left(myCell.Value, 4) = "pos=" Then
            arEquality = Split(myCell, "=")
            arElements = Split(arEquality(1), ";")
            For i = 0 To UBound(arElements)
                arElements(i) = arElements(i) + numberToAdd
            Next
            myCell.Offset(0, 1).Value = arEquality(0) + "=" + Join(arElements, ";")
        End If
        Next
    End Sub
    

    【讨论】:

    • 需要检查pos= 字符串
    • 我知道并且我打算改进它,但我看到 JMax 的答案基本上是相同的解决方案,所以继续下去似乎有点愚蠢。但既然你这么好心评论,我还是会更新代码:-)
    • @JMax:正如你所说,没有错误检查,所以它仍然可以炸毁大时间;希望这不会被用于精确轰炸
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-05-18
    • 2023-04-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多