📌

VBAで改行を取得し、指定した行数まで取得する

2022/06/20に公開

箇条書きの文章を○行目まで表示したいVBA Function

getSomeLines(sentence, lineNumber)
Function getSomeLines(ByVal sentence, ByVal lineNumber)
    Dim setCount As Integer: setCount = 0
    Dim cCnt As Integer: cCnt = 0
    Dim line As String: line = ""
    Dim dispSentence As String: dispSentence = ""
    
    Dim lenStr As Integer
    
    cCnt = InStr(sentence, vbLf)
    If cCnt > 0 Then
    
        Do While cCnt > 0 And setCount <= lineNumber - 1
            setCount = setCount + 1
            'sentenceの文字列長
            lenStr = Len(sentence)
            '最初の改行コードまでの文字数
            cCnt = InStr(sentence, vbLf)
            If cCnt = 0 Then
                dispSentence = dispSentence & sentence
                Exit Do
            End If
            '最初の改行コードまでの文字列を取得
            line = Left(sentence, cCnt)
            '最初の改行コード以降の文字列を取得し、sentenceを上書き
            sentence = Mid(sentence, cCnt + 1, lenStr)
            
            '表示用変数に格納
            dispSentence = dispSentence & line
        Loop
        If cCnt > 0 Then
            dispSentence = dispSentence & " ...(以下省略)"
        End If
        
    Else
        dispSentence = sentence
    End If
    
    getSomeLines = dispSentence
End Function

Discussion