在Excel中使用VBA代碼:
注意:Google如何將一個命令按鈕在工作表上並將其粘貼爲代碼。
Option Explicit
' note: vbNullString is the same as "" (empty string)
Const START_ROW = 1
Const SRC_COL = 1 ' column A
Const DST_COL = 2 ' column B
' this gets triggered when the button is pressed
Private Sub CommandButton1_Click()
' call the routine
Call Go
End Sub
Function Go()
' assume the button is on the sheet to be processed
Dim ws As Excel.Worksheet
Set ws = Excel.ActiveSheet
Dim srcRow As Integer ' current row being processed
Dim dstRow As Integer ' current row to put result in
srcRow = START_ROW: dstRow = START_ROW
' keep going while column 'A' is not blank
While ws.Cells(srcRow, SRC_COL) <> vbNullString
Call Split(ws, ws.Cells(srcRow, SRC_COL), dstRow)
srcRow = srcRow + 1
Wend
End Function
Sub Split(ws As Excel.Worksheet, srcStr As String, ByRef dstRow As Integer)
If (srcStr = vbNullString) Then
'remove comment if you want blanks at the end
' ex. Apple,Banana,
' will create 3 entries, notice the comma at the end
'ws.Cells(dstRow, DST_COL) = vbNullString
'dstRow = dstRow + 1
Exit Sub
endif
' find ","
Dim pos As Integer
pos = InStr(1, srcStr, ",")
If (pos = 0) Then
' no "," - put the whole string
ws.Cells(dstRow, DST_COL) = Trim(srcStr)
dstRow = dstRow + 1
Else
' has "," - put the left part of the string
' ex: apple,banana,carrot
' put "apple"
' continue processing "banana,carrot"
ws.Cells(dstRow, DST_COL) = Trim(Mid(srcStr, 1, pos - 1))
' move to next row and process the right of the string
dstRow = dstRow + 1
Call Split(ws, Mid(srcStr, pos + 1), dstRow)
End If
End Sub
來源
2016-03-10 01:05:30
Ian
您是否嘗試了文本到列,然後複製 - >粘貼特殊 - >移調? –
你甚至可以嘗試錄製自己的文本到列,看看它出現了什麼。 – Jeeped
感謝您的快速響應,但在我的情況下,它不夠。我需要使用公式來完成它,因爲我將它整理到數據驗證列表中 – wiecman