使用macros将标题添加到列数据

我需要一个简单的macros,将列标题值添加到电子表格的列中的内容(最好是指定的值)。

所以如果可能的话,我想在VBA中指定列名(Col1 =“Location”),这样macros就只适用于特定的列。

例如:如果我已经指定“位置”作为macros头应该查找的列标题,并且A1具有“位置”作为头部,则A中的所有内容都需要“位置:”添加到它的前面。 基本上,无论标题是“:”。

所以这:

Location A04B25 A05B89 B58C23 

会是这样的:

 Location Location: A04B25 Location: A05B89 Location: B58C23 

这个macros需要循环遍历每一列,并将列标题的值添加到列表中的值。

这是我试图使用的代码不工作:

 Sub AppendHeader() Dim i, LastCol LastCol = Range("IV1").End(xlToLeft).Column For i = 1 To LastCol If UCase(Cells(1, i).Value) = "Local SKU" Then Cells(1, i).EntireColumn.Append = UCase(Cells(1, i).Value) + ": " End If If UCase(Cells(1, i).Value) = "Supplier's SKU" Then Cells(1, i).EntireColumn.Append = UCase(Cells(1, i).Value) + ": " End If Next End Sub 

这是你正在尝试?

 Option Explicit Sub Sample() Dim ws As Worksheet Dim preString As String Dim lastRow As Long, LastCol As Long, i As Long, j As Long Set ws = Sheets("Sheet1") With ws LastCol = .Cells(1, Columns.Count).End(xlToLeft).Column For i = 1 To LastCol Select Case Trim(UCase(Cells(1, i).Value)) Case "LOCAL SKU", "SUPPLIER'S SKU" lastRow = .Range(Split(Cells(, i).Address, "$")(1) & Rows.Count).End(xlUp).Row preString = .Cells(1, i).Value & ": " For j = 2 To lastRow .Cells(j, i).Value = preString & .Cells(j, i).Value Next j End Select Next i End With End Sub 

SO上也有类似的问题 ,但是我想出了一个不同的VBA解决scheme。 它将根据该列的标题更改列的数字格式(标题行除外)。

要手动执行此操作,可以select格式单元格的“自定义”类别并input

 "Location: "General;"Location: "@ 

这将使“位置:”显示在数字,文字,date等前面。 任何应用于这些单元格的公式都会考虑前缀( Location: :),但假设您只想使用这些值。 使用这种方法,您可以轻松地删除格式,而不是创build第二个子例程来删除前缀。

代码修改了Siddharth的 – 谢谢,先生 – (我没有明确地声明所有的variables,但这是最好的实践)。

 Sub Sample2() Set ws = Sheets("Sheet1") With ws LastCol = .Cells(1, Columns.Count).End(xlToLeft).Column For i = 1 To LastCol lastRow = .Range(Split(Cells(, i).Address, "$")(1) & Rows.Count).End(xlUp).Row preString = .Cells(1, i).Value & ": " Range(Cells(2, i), Cells(lastRow, i)).NumberFormat = _ Chr(34) & preString & Chr(34) & "General;" & _ Chr(34) & preString & Chr(34) & "@" Next i End With End Sub