VBA一鍵拆分字串中的數字與非數字

如:手中有一批這樣的(25ABSC36CAQC1234A )字串,想把其中的數字與非數字拆分開,只需用以下程式碼即可。

***************************************************************************************

Private Sub CommandButton1_Click()

Application。ScreenUpdating = False

Dim a%, i%, ii%, nc%

Dim tmp$, k, c%, gs%: gs = 2

a = [a65536]。End(xlUp)。Row ‘A列中的行數

For i = 1 To a ’單元格迴圈開始

If Cells(i, 1) <> “” Then ‘防止A列中內容為空

Set dic = CreateObject(“scripting。dictionary”) ’建立字典

nc = Len(Cells(i, 1)) ‘獲取單元格長度

For ii = 1 To nc ’開始迴圈單元格中的各個元素

tmp = Mid(Cells(i, 1), ii, 1) ‘設定tmp為單元格中每個元素

dic。Add ii, tmp ’將每個元素剝離後加入字典中

Next ii

k = dic。items ‘設定k為字典內容

tmp = k(0) ’重新設定tmp值,為字典中第一個內容

For c = 1 To dic。Count - 1 ‘迴圈字典中內容,因已設定tmp為第一個,故從1開始迴圈

If IsNumeric(tmp) = IsNumeric(k(c)) Then ’如果tmp與下一個字典內容的型別相同

tmp = tmp & k(c) ‘將tmp與下一個字典內容結合

Else ’否則

Cells(i, gs) = tmp ‘這裡就表示k(c)與tmp不同,所以將tmp寫入單元格中

gs = gs + 1 ’標記要寫入的單元格列數,寫入完成後加1,方便下次再寫入

tmp = k(c) ‘tmp已寫入單元格中,故重新賦值tmp為k(c),因為tmp與k(c)不同了

End If

If c = dic。Count - 1 Then Cells(i, gs) = tmp ’因為最後一個值往後沒有資料了,所以直接寫入單元格

Next c ‘返回字典迴圈

gs = 2 ’資料來源的行數改變,所以列數重新設定為2,即B列

Set dic = Nothing

End If

Next i ‘返回單元格迴圈

Application。ScreenUpdating = True

End Sub

***********************************************************************************

VBA一鍵拆分字串中的數字與非數字

VBA一鍵拆分字串中的數字與非數字

VBA一鍵拆分字串中的數字與非數字

VBA一鍵拆分字串中的數字與非數字

VBA一鍵拆分字串中的數字與非數字