【发布时间】:2021-03-22 21:30:06
【问题描述】:
我正在尝试在工作表中按名称查找两列,即。 “Fruits”列和“Vegetables”列,然后尝试将这些列的合并值粘贴到新列中。
工作表“FruitsVege”
| A | B | C | |
|---|---|---|---|
| 1 | New Column | Fruits | Vegetables |
| 2 | Blank | Apple | Spinach |
| 3 | Blank | Orange | Cabbage |
工作表“FruitsVege”中的所需结果
| A | B | C | |
|---|---|---|---|
| 1 | New Column | Fruits | Vegetables |
| 2 | AppleSpinach | Apple | Spinach |
| 3 | OrangeCabbage | Orange | Cabbage |
我的代码
Sub Merge_B&C()
Dim WrkBk1 As Workbook
Dim WrkBk2 As Workbook
Set WrkBk2 = ActiveWorkbook
Set WrkBk1 = ThisWorkbook
Dim ws2 As Worksheet
Set ws2 = WrkBk2.Sheets(1)
Dim xRg As Range
Dim xRgUni As Range
Dim xFirstAddress As String
Dim xStr As String
On Error Resume Next
' Insert a column in the beginning
ws2.Columns("A:A").Insert Shift:=xlToRight, CopyOrigin:=xlFormatFromLeftOrAbove
'Search for Fruits Column
xStr = "Fruits"
Set xRg = ws2.Range("A1:CA1").Find(xStr, , xlValues, xlWhole, , , True)
If Not xRg Is Nothing Then
xFirstAddress = xRg.Address
Do
Set xRg = ws2.Range("A1:CA1").FindNext(xRg)
If xRgUni Is Nothing Then
Set xRgUni = xRg
Else
Set xRgUni = Application.Union(xRgUni, xRg)
End If
Loop While (Not xRg Is Nothing) And (xRg.Address <> xFirstAddress)
End If
'Search for Vegetables Column
Dim xRg1 As Range
Dim xRgUni1 As Range
Dim xFirstAddress1 As String
Dim xStr1 As String
xStr1 = "Vegetables"
Set xRg1 = ws2.Range("A1:CA1").Find(xStr1, , xlValues, xlWhole, , , True)
If Not xRg1 Is Nothing Then
xFirstAddress = xRg1.Address
Do
Set xRg1 = ws2.Range("A1:CA1").FindNext(xRg1)
If xRgUni1 Is Nothing Then
Set xRgUni1 = xRg1
Else
Set xRgUni1 = Application.Union(xRgUni1, xRg1)
End If
Loop While (Not xRg1 Is Nothing) And (xRg1.Address <> xFirstAddress)
End If
'Select A2
ws2.Range("A2").Select
'Write A2 = B2&C2 and Autofill
With ws2.Range("a2", Range("a" & Rows.Count).End(xlUp))
.FormulaR1C1 = "=RC[xRgUni.Offset(1, 0)]&RC[xRgUni1.Offset(1, 0)]"
End With
End Sub
我试过的是这样的,但它只粘贴值,我不能自动填充整列!如果有人能让我走上正轨,那就太好了。谢谢。
ws2.Range("A2").Value = ((xRgUni.Offset(1, 0).Value) & (xRgUni1.Offset(1, 0).Value))
【问题讨论】:
-
您有多个水果和蔬菜列吗?当您执行此操作时,“=RC[xRgUni.Offset(1, 0)]&RC[xRgUni1.Offset(1, 0)]" 引号内的所有内容都将按字面意思显示在单元格中。
-
@SJR 不,我没有多列。在“FruitsVege”表中,我只有这两列。我需要使列 A 值 = B&C。例如。 A2 = B2&C2 和自动填充。