我有一個Excel表中,有時整個小區有以下內容:解析字符串,並添加一個數字值
pos=51;70;112;111;132;153
注意在單個細胞中的全部內容,也就是說值51;70;112...
是串在一起在一個單元格中,而不是在他們自己的單元格中。
我可以寫一個宏,中包含的關鍵詞"pos="
所有單元格,添加2〜每個值,從而使最終的結果是:
pos=53;72;114;113;134;155
我有一個Excel表中,有時整個小區有以下內容:解析字符串,並添加一個數字值
pos=51;70;112;111;132;153
注意在單個細胞中的全部內容,也就是說值51;70;112...
是串在一起在一個單元格中,而不是在他們自己的單元格中。
我可以寫一個宏,中包含的關鍵詞"pos="
所有單元格,添加2〜每個值,從而使最終的結果是:
pos=53;72;114;113;134;155
這裏是一個代碼,將做到這一點(測試在我的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
請注意,如果您的值格式不正確,我沒有添加錯誤檢查部分。
你知道,你可以很容易地拆分數據而不使用宏,對吧?只需使用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
有它總是5個分號或這是否也不同? – rene 2012-03-06 20:32:39
@rene:實際上,沒關係 – JMax 2012-03-06 20:55:13