循环通过WordsList不能抵消每个集合的数据

时间:2018-05-16 11:03:08

标签: vba excel-vba loops for-loop excel

有点愚蠢的问题可能是一个简单的答案!

我试图遍历数据,我通过分隔符将其拆分,然后想要将每个拆分部分偏移到行中,然后移动到下一行/数据,

这是我的代码:

Dim undelimitedstring As String

    undelimitedstring = AlphaNumericOnly(rng.Value)

    WordsList = Split(undelimitedstring, "Q")

    result = ""
    Count = UBound(WordsList)

    For i = 1 To Count

        Dim ios As Integer
        ios = 0
        Worksheets("Calendar").Range("H" & rng.Row).Activate
        MsgBox (WordsList(i))

        For Each element In WordsList
            Dim n As Integer
            Dim o As Integer
            n = 0
            o = 1
            ActiveCell.Offset(0, n).Value = WordsList(o)
        Next element

    ios = ios + 1
    Next i

如果有人可以提供帮助,那将是晶圆厂!

2 个答案:

答案 0 :(得分:1)

我相信以下内容会按预期执行,它会获取WordsList中的所有值,并将每个值输入到H列的新行中:

Dim undelimitedstring As String

undelimitedstring = AlphaNumericOnly(Rng.Value)

WordsList = Split(undelimitedstring, "Q")

result = ""

For i = 1 To UBound(WordsList)
    NextFreeRow= Worksheets("Calendar").Cells(Worksheets("Calendar").Rows.Count, "H").End(xlUp).Row + 1
    Worksheets("Calendar").Range("H" & NextFreeRow).Value = WordsList(i)
Next i

<强>更新

下面修改后的代码会将WordList中的两个值添加到相邻单元格中的一行,然后移动到下一行并添加下两个值,依此类推:

Dim undelimitedstring As String

undelimitedstring = AlphaNumericOnly(Rng.Value)

WordsList = Split(undelimitedstring, "Q")

result = ""
NextFreeRow = Worksheets("Calendar").Cells(Worksheets("Calendar").Rows.Count, "H").End(xlUp).Row + 1
Counter = 0
For i = 1 To UBound(WordsList)
    Counter = Counter + 1
    Worksheets("Calendar").Range("H" & NextFreeRow).Value = WordsList(i)
    If Counter = 2 Then
    Worksheets("Calendar").Range("I" & NextFreeRow).Value = WordsList(i)
        NextFreeRow = NextFreeRow + 1
        Counter = 0
    End If
Next i

答案 1 :(得分:0)

这里有点猜测你的意思

  

我通过分隔符将其拆分,然后将每个拆分部分偏移到   行

此代码将采用 123 456 Q 654 321 987 Q 789 012 之类的字符串,并将其拆分为三行:

  • 123 456
  • 654 321 987
  • 789 012

使用:
如果A1包含 123 456 Q 654 321 987 Q 789 012 ,则突出显示C1:C3并输入=SplitString(A1)作为数组公式。

Public Function SplitString(Target As Range, Optional Delim As String = "Q") As Variant

    SplitString = Application.WorksheetFunction.Transpose(Split(Target, Delim))

End Function

如果您想将它作为一个过程而不是函数使用:

Sub Test()

    SplitString_2 Sheet1.Range("A1"), Sheet1.Range("D1")

End Sub

Public Sub SplitString_2(Target As Range, Destination As Range, Optional Delim As String = "Q")

    Dim vSplit As Variant
    Dim lElements As Long

    vSplit = Split(Target, Delim)
    lElements = UBound(vSplit) + 1 'Assumes LBound = 0

    Destination.Resize(lElements) = Application.WorksheetFunction.Transpose(vSplit)

End Sub