VBA / Excel:将列拆分为40个字符和800个字符,全字

时间:2018-04-09 17:59:27

标签: excel-vba vba excel

我在A栏中有30-120个字符串。我需要B列占用前40个整个单词字符和C列来取剩余字符800.

我一直在研究这个问题的解决方案,我所看到的一切都与我正在寻找的东西略有不同。我试图在VBA中执行此操作以简化流程,因为我有30个Spreadsheets,每个包含超过1500行。

如果我有单词Fittings,则第一个i是第40个字符......这个单词可以被推入下一列吗?在第一列中留下38个字符

Example of what I am looking for:

2 个答案:

答案 0 :(得分:1)

所以我有这个凌乱的代码。它可能不是(不是)最优的,但它可以按照您的需要工作。

Sub SeparateString()

Dim str As String: str = Range("A2")
Dim strLeft, strRight As String
Dim i As Integer: i = 2
Dim lenLeft As Integer

Do While str <> ""
    str = Range("A" & i)
    strLeft = ""
    strRight = ""
    lenLeft = 40


    Do While Mid(str, lenLeft, 1) <> " "
        lenLeft = lenLeft + 1
        If lenLeft > 20000 Then GoTo Out
    Loop
Out:
    strLeft = Left(str, lenLeft)

    On Error Resume Next
        strRight = Right(str, Len(str) - lenLeft)
    On Error GoTo 0

    Range("B" & i) = strLeft
    Range("C" & i) = strRight

    i = i + 1
Loop

End Sub

输出:

enter image description here

答案 1 :(得分:0)

InStrRev将成为你的朋友。

dim p as long, tmp as string, i as long

with worksheets("sheet1")
    for i=1 to .cells(.rows.count, "A").end(xlup).row
        tmp = .cells(i, "A").value2
        p = instrrev(tmp & chr(32), chr(32), 40)
        .cells(i, "B") = left(tmp, p-1)
        if p < len(tmp) then .cells(i, "C") = mid(tmp, p+1)
    next i
end with