如何将文本框内容添加到Excel单元格且不覆盖并实现换行?
Got it, let's sort this out for you! The problem with using SendKeys here is that it's designed to simulate keyboard input in the active window—and when you're directly setting a cell's .Value via VBA, you're not in cell edit mode at all. That's why SendKeys("%{ENTER}") does nothing here, plus SendKeys is super unreliable in general (it depends on window focus, which can shift unexpectedly).
Instead, use VBA's built-in line break constants to add new entries on separate lines in the cell. Here's how to do it properly:
1. Add new entry below existing content
This appends the textbox value to the end of the cell, on a new line:
Dim targetCell As Range Set targetCell = ActiveCell.Offset(0, 23) ' Check if the cell is empty to avoid an extra leading line break If targetCell.Value <> "" Then targetCell.Value = targetCell.Value & vbNewLine & MASCACIncomingRef.Value Else targetCell.Value = MASCACIncomingRef.Value End If
2. Add new entry above existing content
If you want the newest entry to show up at the top of the cell:
Dim targetCell As Range Set targetCell = ActiveCell.Offset(0, 23) ' Check if the cell is empty to avoid an extra trailing line break If targetCell.Value <> "" Then targetCell.Value = MASCACIncomingRef.Value & vbNewLine & targetCell.Value Else targetCell.Value = MASCACIncomingRef.Value End If
Key Notes:
vbNewLineis a VBA constant that inserts the correct line break character for your operating system (works for both Windows and Mac Excel). You can also usevbCrLf(carriage return + line feed) if you specifically need Windows-style line breaks—both will work for cell line breaks in Excel.- If you want the cell to display the line breaks visually, right-click the cell > Format Cells > Alignment > check Wrap Text. Even if you don't enable wrap text, the line breaks are still stored in the cell value, so they'll show up when you use the content in your form's table display.
Forget SendKeys for this kind of cell content manipulation—it's never the right tool for direct value assignments. The above approach is clean, reliable, and exactly what you need for your table display use case.
内容的提问来源于stack exchange,提问作者Badda_Bing

