VBA 宏在新列中连接 2 列

VBA macro concatenate 2 columns in new column

我想创建一个宏来插入带有列名称(BL 和容器)的新列,然后在新插入的列中连接 2 列。 在这个我命名为 BL & Container 的专栏中,是一个添加了我的宏的新专栏。 此外,我希望宏连接 H 列和 F 列中存在的值,宏应该按列名找到 H 列和 F 列,并将它们连接到新插入的 I 列中。

下面是我的代码

Sub insert_conc()

Dim ColHe As Range
Dim FindCol As Range
Dim con As String
Dim x As Long


Set FindCol = Range("1:1") 'Looks in entire first row.
Set ColHe = FindCol.Find(what:="BL/AWB/PRO", After:=Cells(1, 1))
  
With ActiveWorkbook.Worksheets("WE")

  ColHe.Offset(0, 1).EntireColumn.Insert
  ColHe.Offset(0, 1).Value = "WER"
  'x = Range("A" & Rows.Count).End(xlUp).Row
  con = "=H2&""-""&F2"
  ColHe.Resize(x - 1).Formula = con
    
End With

Application.ScreenUpdating = True


End Sub

[![代码错误][3]][3]

在此代码行中“con =”=H2&“”-”“&F2””请告知我如何更新列名称而不是 H2 和 F2 宏应该找到列 H2 和 F2 header 名称然后连接新插入的列 I BL & 容器中的值。请指教

请使用下一个改编代码:

Sub insert_conc()
 Dim sh As Worksheet, x As Long, ColHe As Range
 Dim FindCol As Range, con As String, firstCell As Range

 Set sh = Worksheets("LCL")
 x = sh.Range("A" & sh.rows.count).End(xlUp).row

 Set FindCol = sh.Range("1:1") 'Looks in entire first row.
 Set ColHe = FindCol.Find(what:="BL/AWB/PRO", After:=sh.cells(1, 1))

  ColHe.Offset(0, 1).EntireColumn.Insert
  ColHe.Offset(0, 1).value = "BL & Container"
  Set firstCell = ColHe.Offset(1, -2) ' determine the cell to replace F2

  con = "=" & ColHe.Offset(1).Address(0, 0) & "&" & firstCell.Address(0, 0)
  ColHe.Offset(1, 1).Resize(x - 1).Formula = con
End Sub

同样值得一提的是,只有在 End with 之前的代码行中使用 With ActiveWorkbook.Worksheets("LCL") 才有意义。而你的代码并没有那样做。。。之前应该用过,为了处理合适的sheet,即使不是active的.