简体   繁体   English

使用Excel VBA的子字符串

[英]Substring with Excel VBA

I have been using this code as a starting point: https://danwagner.co/how-to-transpose-horizontal-data-to-vertical-data-for-easy-pivot-tables/ 我一直以这段代码为起点: https//danwagner.co/how-to-transpose-horizo​​ntal-data-to-vertical-data-for-easy-pivot-tables/

One one of my cells Ax (x referring to the number), the content is ABCDEFGHI and I want to substring the cells every 2 characters, and the last set is 3 characters. 我的一个单元格Ax(x代表数字),内容为ABCDEFGHI,我想每2个字符对这些单元格进行子字符串化,最后一组为3个字符。 Final result looks like: 最终结果如下:

AB CD EF GHI AB CD EF GHI

At line 44, using the variable 在第44行,使用变量

varDetails = .Range(.Cells(lngIdx, 1), .Cells(lngIdx, 4)) 

and think that is where I need to modify the code. 并认为这是我需要修改代码的地方。 I am not fluent enough with VBA and need some help. 我对VBA不够流利,需要一些帮助。

To split the data from your string you can use the following code 要从字符串中拆分数据,可以使用以下代码

Sub SplitStringEveryTwoCharacters()
    Dim arrayWithValuesByTwo() As String
    Dim myString As String

    'Just replace with your data
    myString = "ABCDEFGHIJKLM"

    'Resize
    ReDim arrayWithValuesByTwo(Len(myString) - 1)

    'For each 2 character in string
    For i = 1 To Len(myString) Step 2
        'Add in array
        If (i <= Len(myString) - 1) Then
            arrayWithValuesByTwo(i - 1) = Mid$(myString, i, 2)
        End If

        If (i = Len(myString)) Then
            arrayWithValuesByTwo(i - 1) = Mid$(myString, i, 1)
        End If
    Next
End Sub

What you need to change 您需要改变的地方

Here I have set my string into a variable with myString = "ABCDEFGHIJKLM" but you can easily change this and take it directly from a cell with something like myString = Range("A5") . 在这里,我已将字符串设置为myString = "ABCDEFGHIJKLM"的变量,但是您可以轻松地更改它,并直接从带有myString = Range("A5")类的单元格中获取它。

You can access you data with arrayWithValuesByTwo(1) for example. 例如,您可以使用arrayWithValuesByTwo(1)访问数据。 Just loop through it to get all of the values. 只需循环遍历即可获取所有值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM