首页 > 解决方案 > VBA在一定长度上拆分列?

问题描述

我有一个问题与下面的这个线程链接几乎完全相同:

Excel VBA将特定长度的列拆分为多行

但是,如果我想在拆分之前查找最后一个分隔符怎么办?

示例:长度要求小于 10。

我的字符串是:11、3344、5566 结果将是:第 1 行:11,3344,第 2 行:5566

基本上我不需要正好是 10 个字符(最多应该是 10 个字符),但我需要在它达到 10 个字符之前考虑最后一个分隔符。请帮忙

标签: excelvba

解决方案


从 1000 个字符开始并向后循环遍历文本以检查当前字符是否等于您想要的分隔符,如果不是则继续向后循环。如果它等于分隔符,则停止循环并获取位置。

Sub tester():
    ''Application.SendKeys "^g ^a {DEL}"
    Dim last_ctr As Variant
    Dim current_char As Variant
    Dim final_char As Variant
    Dim limit As Variant
    Dim my_delimiter as Variant

    '' your limit on the text
    limit = 1000
    my_delimiter = ","

    test = ActiveSheet.Range("A1")
    '' loop backwards from the string
    For x = limit To 0 Step -1
        '' check the current char if it is equal to what you want
        current_char = Mid(test, x, 1)
        If current_char = my_delimiter Then
            '' get the current position of the loop
            final_char = x
            Exit For
        End If
    Next x
    End Sub

检索到位置后,在其上(final_char)使用Left命令

Left(test, final_char)

推荐阅读