如何在每个列的字符数等于20的范围内为每个列添加空格?

时间:2019-03-26 20:44:13

标签: excel vba

我使用了一个程序,每个程序只能接收20个字符的数据。每列的每个单元格具有相同数量的字符,但从1到8不等。无论如何,是否需要在每个单元格中输入空格,以使它们加起来最多20个字符?

NVL(CAST(substr(DESCRLONG, 1, 4000) as VARCHAR2(4000)), ' ') AS CLOBPART1,  
NVL(CAST(substr(DESCRLONG, 4001, 4000) as VARCHAR2(4000)), ' ') AS CLOBPART2,  
NVL(CAST(substr(DESCRLONG, 8001, 4000) as VARCHAR2(4000)), ' ') AS CLOBPART3,  
NVL(CAST(substr(DESCRLONG, 12001, 4000) as VARCHAR2(4000)), ' ') AS CLOBPART4,  
NVL(CAST(substr(DESCRLONG, 16001, 4000) as VARCHAR2(4000)), ' ') AS CLOBPART5,  
NVL(CAST(substr(DESCRLONG, 20001, 4000) as VARCHAR2(4000)), ' ') AS CLOBPART6,  
NVL(CAST(substr(DESCRLONG, 24001, 4000) as VARCHAR2(4000)), ' ') AS CLOBPART7,  
NVL(CAST(substr(DESCRLONG, 28001, 4000) as VARCHAR2(4000)), ' ') AS CLOBPART8  

寻找一种更简单的方法来实现此目的,而不是使每列变暗(因为有23列)并对每列执行if语句

2 个答案:

答案 0 :(得分:0)

尝试一下:

Sub tgr()

    'Change this to be the columns you need to adjust
    Const sColumns As String = "A:D,F:F"

    Dim wb As Workbook
    Dim ws As Worksheet
    Dim rArea As Range
    Dim rData As Range
    Dim rLast As Range
    Dim aData() As Variant
    Dim i As Long, j As Long

    Set wb = ThisWorkbook
    Set ws = wb.Worksheets("osbstd")

    For Each rArea In ws.Range(sColumns).Areas
        Set rLast = rArea.Find("*", rArea.Cells(1), xlValues, , , xlPrevious)
        If Not rLast Is Nothing Then
            With rArea.Resize(rLast.Row)
                If .Cells.Count = 1 Then
                    ReDim aData(1 To 1, 1 To 1)
                    aData(1, 1) = .Value
                Else
                    aData = .Value
                End If
                For i = 1 To UBound(aData, 1)
                    For j = 1 To UBound(aData, 2)
                        If Len(aData(i, j)) > 0 Then aData(i, j) = Left(aData(i, j) & Space(20), 20)
                    Next j
                Next i
                .Value = aData
                Erase aData
            End With
        End If
    Next rArea

End Sub

答案 1 :(得分:0)

对我来说,最简单的方法是这样的:

Dim result As String
For j = 1 To 23
    For i = 1 To 10000
        result = Cells(i, j).Value
        Do While Len(result) < 20
            result = result & " "
        Loop
        Cells(i, j).Value = result
    Next i
Next j