Len(列(lastColumn +“:”+ c))

时间:2016-05-26 08:37:43

标签: excel vba excel-vba

我已经把这段代码搞砸了一段时间了,我似乎仍然无法让它运行。

我遇到问题的部分代码是:

TempW = Len(Columns(lastColumn + ":" + c))

我正在尝试根据列获取位于特殊单元格内的文本的长度,并将所有长度连接成一个字符串。

示例,7,8,2,13,40

我希望输出是这样的,因为我想将它用作像CWSize = Array(CWStore)这样的数组。

列数不是常数。

这是我的代码:

Sub testColumnLen()

    Dim CWArray As Variant, CWSize As String, TempW As Long, c As Integer, lastColumn As Long
    Dim CWStore As String

    lastColumn = ActiveSheet.Cells(1, Columns.Count).End(xlToLeft).Column

    c = 1
    TempW = Len(Columns(lastColumn + ":" + c))
    c = 2
    CWStore = TempW
    Do While c < lastColumn
        TempW = Len(Columns(lastColumn + ":" + c))
        CWStore = CWStore + "," + TempW
        c = c + 1
    Loop
    CWSize = Array(CWStore)
    CWArray = CWSize
    Debug.Print CWArray
End Sub

2 个答案:

答案 0 :(得分:2)

更新了您的代码:

Sub testColumnLen()

    Dim CWSize As Variant, TempW As Long, c As Integer, lastColumn As Long
    Dim CWStore As String, i As Long

    lastColumn = ActiveSheet.Cells(1, Columns.Count).End(xlToLeft).Column

    c = 1
    Do While c <= lastColumn
        TempW = Len(Cells(1, c))
        If CWStore = "" Then
            CWStore = TempW
        Else
            CWStore = CWStore & "," & TempW
        End If
        c = c + 1
    Loop
    Debug.Print CWStore    '---> this will give you comma separated values

    CWSize = Split(CWStore, ",")
    For i = LBound(CWSize) To UBound(CWSize)
        Debug.Print CWSize(i)    '---> this will give you individual lengths of cell
    Next i
End Sub

答案 1 :(得分:1)

试试这个

Option Explicit

Sub testColumnLen()
    Dim CWArray As Variant
    Dim CWStore As String
    Dim cell As Range

    With ActiveSheet

        For Each cell In .Range("A1", .Cells(1, .Columns.Count).End(xlToLeft))
            CWStore = CWStore & Len(cell) & " "
        Next cell

    End With
    CWArray = Split(Left(CWStore, Len(CWStore) - 1))
End Sub

或者您可能需要将最终数组设置为

CWArray = Array(Left(CWStore, Len(CWStore) - 1))