我的问题实际上很简单,尽管我似乎无法解决。
例如
在单元格A中,我有文字“苹果”
在B C和D单元格中,我都有文字
B = „Bananas“
C = „Pears“
D = „Grapes“
我想选择B,C和D单元格并将其粘贴到A中以获得
A = „Apples, Bananas, Pears, Grapes“
单元格A和单元格B,C和D都发生了变化,因此我无法连接/使用简单的连接功能,例如连接A&B&C&D。
该功能应类似于单击相应的单元格,例如B,选择单词,按CTRL + C,然后单击A单元格,将光标置于“ Apples”后面,然后按CTRL + V。
我搜索了上面提到的问题,但是只发现了一些有关使用数据对象将多个单元格的内容作为文本复制到剪贴板的事情。
您知道如何解决此问题吗?
谢谢!
————
我这边的一个简单尝试是将范围复制到单词doc中,选择单词doc中的所有内容,然后将其复制并粘贴到单元格中
Option Explicit
Sub CopyInCell()
Sheets("Sheet1").Activate
With Selection.Interior
.Pattern = xlSolid
.PatternColorIndex = xlAutomatic
.Color = 5287936
.TintAndShade = 0
.PatternTintAndShade = 0
End With
Selection.Copy
Windows("Sheet2").Activate
SendKeys "{F2}", True
Application.SendKeys ("%~"), True
Application.SendKeys ("^v"), True
End Sub
嵌套步骤是使粘贴工作自动化/使我可以简单地选择一个单元格,将粘贴的文本添加到单元格文本的末尾。
尝试结合使用Pehs方法和切换工作簿
Sub insert_change()
Dim Concatenated As String
Dim Cell As Range
Dim Cell2 As Range
For Each Cell In Selection.Cells 'go through all cells within the selection
If Concatenated = vbNullString Then
Concatenated = Cell.Value
Else
Concatenated = Concatenated & ", " & Cell.Value
End If
Next Cell
Windows("Book2.xlsx").Activate
Sheets("A").Activate
Cell2 = Selection.Cells.Value
Concatenated = Cell2 & ", " & Concatenated
Selection.Cells.Value = Concatenated
结束子
结果是运行时错误13,行
中的类型不匹配Cell2 = Selection.Cells.Value
这可能是什么原因? 当我手动切换到该工作表时,我选择了正确的单元格。
谢谢!
答案 0 :(得分:2)
如果您的单元格全部都连续一列(中间没有空白单元格),则可以使用:
Selection.Cells(1).Value = Join(WorksheetFunction.Transpose(Selection.Value), ", ")
或者,如果它们不是连续的或连续的,则可以使用以下内容:
Dim Concatenated As String
Dim Cell As Range
For Each Cell In Selection.Cells 'go through all cells within the selection
If Concatenated = vbNullString Then
Concatenated = Cell.Value 'collect the first value
Else
Concatenated = Concatenated & ", " & Cell.Value 'concatenate all other values comma separated
End If
Next Cell
Selection.Cells(1).Value = Concatenated 'write the concatenated string into the first cell of the selection
请注意,您必须选择所有单元格A,B,C和D,然后运行宏。然后它将结果写入单元格A。
或者将其写入/追加到另一个工作簿单元中,使用以下内容代替上面的最后一行。
Workbooks("Book2").Worksheets("A").Activate 'workbook and worksheet to select from
Dim AppendRange As Range
On Error Resume Next 'if next line throws error then no range was selected
Set AppendRange = Application.InputBox(Prompt:="Select the destination cell to append", Title:="Select", Default:=Selection.Address, Type:=8)
On Error GoTo 0
If Not AppendRange Is Nothing Then
If AppendRange.Cells.Count > 1 Then 'check if more than one cell was selected
MsgBox "Only selection of one destination cell is allowed.", vbCritical, "Cannot append"
Exit Sub
End If
AppendRange.Value = AppendRange.Value & IIf(AppendRange.Value <> vbNullString, ", ", vbNullString) & Concatenated
End If
如果使用此替代方法,则需要先选择源工作表的单元格,然后启动宏。它将询问用户哪个将是目标单元格,然后将所有值连接到目标。