Excel VBA 单元格设置好为自动换行。问:怎样获取单元格内共有多少行?怎样获取单元格内各行文
ExcelVBA单元格设置好为自动换行。问:怎样获取单元格内共有多少行?怎样获取单元格内各行文本?...
Excel VBA 单元格设置好为自动换行。问:怎样获取单元格内共有多少行?怎样获取单元格内各行文本?
展开
1个回答
展开全部
选中目标单元格,执行下面的过程即可
Option Explicit
Sub GetMultiLine()
Dim OStr As String, OLen As Integer
OStr = ActiveCell.Value
OLen = Len(OStr)
If OLen = 0 Then
MsgBox "空单元格"
Exit Sub
End If
'单元格非空时获取换行符,并获取单元格内各行文本
Dim arrStr() As String, CvtASC As Long, i As Integer
Dim arrLineLoc() As Integer
Dim arrNewStr() As String, j As Integer
For i = 1 To OLen
ReDim Preserve arrStr(1 To i)
arrStr(i) = Mid(OStr, i, 1)
CvtASC = Asc(arrStr(i))
If CvtASC = 10 Then
j = j + 1
ReDim Preserve arrLineLoc(1 To j)
arrLineLoc(j) = i
End If
Next
j = j + 1
ReDim Preserve arrLineLoc(1 To j)
arrLineLoc(j) = OLen + 1
For i = 1 To j
ReDim Preserve arrNewStr(1 To i)
If i = 1 Then
arrNewStr(i) = Mid(OStr, 1, arrLineLoc(i) - i)
Else
arrNewStr(i) = Mid(OStr, arrLineLoc(i - 1) + 1, arrLineLoc(i) - arrLineLoc(i - 1) - 1)
End If
Next
'输出结果
Dim NoOfLine As Integer, OutStr As String
NoOfLine = UBound(arrNewStr)
For i = 1 To NoOfLine
OutStr = OutStr & arrNewStr(i) & vbCr
Next
OutStr = "单元格内共有 " & NoOfLine & "行" & vbCr & OutStr
MsgBox OutStr
End Sub
更多追问追答
追问
cvtASC as long,
运行时,显示type块外部的语句无效
注意:单元格为设置好了的自动换行格式,在输入内容后会自动换行为多行显示,获取显示有几行的代码
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询