Vba 通过代码在包装单元格中插入换行符
是否可以通过VBA代码在包装单元格中插入换行符?(与手动输入数据时执行Alt Enter类似)Vba 通过代码在包装单元格中插入换行符,vba,excel,Vba,Excel,是否可以通过VBA代码在包装单元格中插入换行符?(与手动输入数据时执行Alt Enter类似) 我已经通过VBA代码将单元格的wrap text属性设置为True,并且也通过VBA代码将数据插入其中 是的。与AltEnter等效的VBA是使用换行符: ActiveCell.Value = "I am a " & Chr(10) & "test" 请注意,这会自动将WrapText设置为True 证明: 您还可以使用对应于Chr(13)&Chr(10)的vbCrLf,是有两种方法
我已经通过VBA代码将单元格的wrap text属性设置为True,并且也通过VBA代码将数据插入其中 是的。与AltEnter等效的VBA是使用换行符:
ActiveCell.Value = "I am a " & Chr(10) & "test"
请注意,这会自动将WrapText
设置为True
证明:
您还可以使用对应于
Chr(13)
&Chr(10)
的vbCrLf
,是有两种方法可以添加换行符:
vbCrLf
中的现有函数,例如:
将文本变暗为字符串
text=“你好”&vbCrLf&“世界!”
工作表(1)。单元格(1,1)=文本Chr()
函数并传递ASCII字符13和10以添加换行符,如下所示:
将文本变暗为字符串
text=“你好”&Chr(13)&Chr(10)&World!”
工作表(1)。单元格(1,1)=文本在这两种情况下,单元格(1,1)或A1中的输出都是相同的。只需在文本框中按Ctrl+Enter键即可。我知道这个问题很老,但由于我有相同的需求,在搜索SO和google后,我找到了一些答案,但没有任何可用的。因此,通过这些片段和片段,我制定了我的解决方案,我在这里分享 我需要什么
Sub-SplitLineTest()
将文本范围变暗为范围
设置TextRange=FeuilTest.Cells(2,2)
'将要换行的文本放在多个单元格中,然后通过它
将新文本设置为字符串
NewText=SetCRtoEOL(TextRange.Value2,TextRange.Font.Name,TextRange.Font.Size,xlwidthttopixs(TextRange.ColumnWidth)-5)'-5考虑文本左右两个白色像素+1个网格像素
'复制单个单元格中的每个文本行
Dim Resultar()作为字符串
resultar()=Split(NewText,Chr(10))
TextRange.Offset(2,0).Resize(UBound(resultar)+1,1).Value2=WorksheetFunction.Transpose(resultar())
端接头
函数xlwidthtopix(ByVal xlWidth为双精度)的长度
'f转换Excel列宽大小的操作,以Excel单位(范围.ColumnWidth)表示,以像素为单位
'参数:-xlWidth:这是列Excel单位的宽度
'Return:-列的大小(以像素为单位)
Dim PXFONTWITHMAX最大长度
'Xl列大小与工作簿默认字符串配置有关,取决于字符“0”的像素大小。我们需要收集它
使用此工作簿。样式(“正常”)。字体
pxFontWidthMax=pxGetStringW(“0”、.Name、.Size)”获取“0”字符的大小(以像素为单位)
以
“现在,我们可以进行计算了
xlWidthToPixs=工作表功能.地板精度(((256*xlWidth+工作表功能.地板精度(128/pxFontWidthMax))/256)*pxFontWidthMax)+5
端函数
函数SetCRtoEOL(ByVal Original作为字符串,ByVal FontName作为字符串,ByVal FontSize作为变量,ByVal pxavalw)作为字符串
函数的作用是在需要时在单词之间放置一些CR字符,使文本适合给定数量的像素。
如果某些单词太长,无法放入给定的宽度,它们将不会被剪切,并且会超出给定的限制。
'该函数以递归方式工作。每次找到行尾时,它都会用剩余的文本调用自己,直到找到为止。
'当文本适合给定空间而无需再截断时,递归过程结束
'参数:-原始:要匹配的文本
'-FontName:字体的名称
'-FontSize:字体的大小
'-pxavalw:Available width(以像素为单位),我们需要使文本适合
'Return:-在需要剪切文本以适应宽度的地方,使用CR替换空格的原始文本
'如果我们得到一个空字符串,那么没有什么可以做的,因此我们返回一个空字符串
如果Original=vbNullString,则退出函数
变暗pxTextW尽可能长
'如果文本适合,可能是原始文本,也可能是递归的结束。除了返回文本外,没有什么可做的
pxTextW=pxGetStringW(原始、FontName、FontSize)
如果pxTextWSub test()
Dim c As Range
Set c = ActiveCell
c.WrapText = False
MsgBox "Activcell WrapText is " & c.WrapText
c.Value = "I am a " & Chr(10) & "test"
MsgBox "Activcell WrapText is " & c.WrapText
End Sub
Sub SplitLineTest()
Dim TextRange As Range
Set TextRange = FeuilTest.Cells(2, 2)
'Take the text we want to wrap then past it in multi cells
Dim NewText As String
NewText = SetCRtoEOL(TextRange.Value2, TextRange.Font.Name, TextRange.Font.Size, xlWidthToPixs(TextRange.ColumnWidth) - 5) '-5 to take into account 2 white pixels left and right of the text + 1 pixel for the grid
'Copy each of the text lines in an individual cell
Dim ResultArr() As String
ResultArr() = Split(NewText, Chr(10))
TextRange.Offset(2, 0).Resize(UBound(ResultArr) + 1, 1).Value2 = WorksheetFunction.Transpose(ResultArr())
End Sub
Function xlWidthToPixs(ByVal xlWidth As Double) As Long
'Fonction to convert the size of an Excel column width expressed in Excel unit(Range.ColumnWidth) in pixels
'Parameters : - xlWidth : that is the width of the column Excel unit
'Return : - The size of the column in pixels
Dim pxFontWidthMax As Long
'Xl Col sizing is related to workbook default string configuration and depends of the size in pixel from char "0". We need to gather it
With ThisWorkbook.Styles("Normal").Font
pxFontWidthMax = pxGetStringW("0", .Name, .Size) 'Get the size in pixels of the '0' character
End With
'Now, we can make the calculation
xlWidthToPixs = WorksheetFunction.Floor_Precise(((256 * xlWidth + WorksheetFunction.Floor_Precise(128 / pxFontWidthMax)) / 256) * pxFontWidthMax) + 5
End Function
Function SetCRtoEOL(ByVal Original As String, ByVal FontName As String, ByVal FontSize As Variant, ByVal pxAvailW) As String
'Function aiming to make a text fit into a given number of pixels, by putting some CR char between words when needed.
'If some words are too longs to fit in the given width, they won't be cut and will get out of the limits given.
'The function works recursively. Each time it find an End Of Line, it call itself with the remaining text until.
'The recursive process ends whent the text fit in the given space without needing to be truncated anymore
'Parameters : - Original : The text to fit
' - FontName : Name of the font
' - FontSize : Size of the font
' - pxAvailW : Available width in pixels in wich we need to make the text fit
'Return : - The orignal text with CR in place of spaces where the text needs to be cut to fit the width
'If we got a null string, there is nothing to do so we return a null string
If Original = vbNullString Then Exit Function
Dim pxTextW As Long
'If the text fit in, may be it's the original or this is end of recursion. Nothing to do more than returne the text back
pxTextW = pxGetStringW(Original, FontName, FontSize)
If pxTextW < pxAvailW Then
SetCRtoEOL = Original
Exit Function
End If
'The text doesn't fit, we need to find where to cut it
Dim WrapPosition As Long
Dim EstWrapPosition As Long
EstWrapPosition = Len(Original) * pxAvailW / pxTextW 'Estimate the cut position in the string given to a proportion of characters
If pxGetStringW(Left(Original, EstWrapPosition), FontName, FontSize) < pxAvailW Then
'Text to estimated wrap position fits in, we try to see if we can fits some more words
WrapPosition = FindMaxPosition(Original, FontName, FontSize, pxAvailW, EstWrapPosition)
End If
'If WrapPosition = 0, we didn't get a proper place yet, we try to find the previous white space
If WrapPosition = 0 Then
WrapPosition = FindMaxPositionRev(Original, FontName, FontSize, pxAvailW, EstWrapPosition)
End If
'If WrapPosition is still 0, we are facing a too long word for the pxAvailable. We'll cut after this word what ever. (Means we must search for the first white space of the text)
If WrapPosition = 0 Then
WrapPosition = InStr(Original, " ")
End If
If WrapPosition = 0 Then
'Words too long to cut, but nothing more to cut, we return it as is
SetCRtoEOL = Original
Else
'We found a wrap position. We recurse to find the next EOL and construct our response by adding CR in place of the white space
SetCRtoEOL = Left(Original, WrapPosition - 1) & Chr(10) & SetCRtoEOL(Right(Original, Len(Original) - WrapPosition), FontName, FontSize, pxAvailW)
End If
End Function
Function FindMaxPosition(ByVal Text As String, ByVal FontName As String, ByVal FontSize As Variant, ByVal pxAvailW, ByVal WrapPosition As Long) As Long
'Function that finds the maximum number of words fitting in a given space by adding words until it get out of the maximum space
'The function is inteded to work on text with a "guessed" wrap position that fit in the space allowed
'The function is recursive. Each time it guesses a new position and the word still fits in the space, it calls itself with a further WrapPosition
'Parameters : - Text : The text to fit
' - FontName : Name of the font
' - FontSize : Size of the font
' - pxAvailW : Available width in pixels in wich we need to make the text fit
' - WrapPosition : The initial wrap position, positionned someware in the text (WrapPosition < len(Text)) but inside pxAvailW
'Return : - The position were the text must be wraped to put as much words as possible in pxAvailW, but without getting outside of it. If no position can be found, returns 0
Dim NewWrapPosition As Long
Static isNthCall As Boolean
'Find next Whitespace position
NewWrapPosition = InStr(WrapPosition, Text, " ")
If NewWrapPosition = 0 Then Exit Function 'We can't find a wrap position, we return 0
If pxGetStringW(Left(Text, NewWrapPosition - 1), FontName, FontSize) < pxAvailW Then '-1 not to take into account the last white space
'It still fits, we can try on more word
isNthCall = True
FindMaxPosition = FindMaxPosition(Text, FontName, FontSize, pxAvailW, NewWrapPosition + 1)
Else
'It doesnt fit. If it was the first call, we terminate with 0, else we terminate with previous WrapPosition
If isNthCall Then
'Not the first call, we have a position to return
isNthCall = False 'We reset the static to be ready for next call of the function
FindMaxPosition = WrapPosition - 1 'Wrap is at the first letter of the word due to the function call FindMax...(...., NewWrapPosition + 1). The real WrapPosition needs to be minored by 1
Else
'It's the first call, we return 0 | Strictly speaking we can remove this part as FindMaxPosition is already 0, but it make the algo easier to read
FindMaxPosition = 0
End If
End If
End Function
Function FindMaxPositionRev(ByVal Text As String, ByVal FontName As String, ByVal FontSize As Variant, ByVal pxAvailW, ByVal WrapPosition As Long) As Long
'Function working backward of FindMaxPosition. It finds the maximum number of words fitting in a given space by removing words until it fits the given space
'The function is inteded to work on text with a "guessed" wrap position that fit in the space allowed
'The function is recursive. Each time it guesses a new position and the word still doesn't fit in the space, it calls itself with a closer WrapPosition
'Parameters : - Text : The text to fit
' - FontName : Name of the font
' - FontSize : Size of the font
' - pxAvailW : Available width in pixels in wich we need to make the text fit
' - WrapPosition : The initial wrap position, positionned someware in the text (WrapPosition < len(Text)), but outside of pxAvailW
'Return : - The position were the text must be wraped to put as much words as possible in pxAvailW, but without getting outside of it. If no position can be found, returns 0
Dim NewWrapPosition As Long
NewWrapPosition = InStrRev(Text, " ", WrapPosition)
'If we didn't found white space, we are facing a "word" too long to fit pxAvailW, we leave and return 0
If NewWrapPosition = 0 Then Exit Function
If pxGetStringW(Left(Text, NewWrapPosition - 1), FontName, FontSize) >= pxAvailW Then '-1 not to take into account the last white space
'It still doesnt fits, we must try one less word
FindMaxPositionRev = FindMaxPositionRev(Text, FontName, FontSize, pxAvailW, NewWrapPosition - 1)
Else
'It fits, we return the position we found
FindMaxPositionRev = NewWrapPosition
End If
End Function