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

时间:2012-05-17 17:23:33

标签: excel vba excel-vba excel-2007

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

因此,如果可能,我想在VBA中指定列名称(Col1 =" Location"),以便宏仅应用于特定列。

实施例: 如果我已指定,"位置"作为列标题,宏应该查找,A1具有"位置"作为标题,然后A中的所有内容都需要,"位置:"添加到它的前面。 基本上,无论标题是+":"。

所以这个:

Location
A04B25
A05B89
B58C23

会是这样的:

Location
Location: A04B25
Location: A05B89
Location: B58C23

此宏需要遍历每一列,并将该列标题值添加到列表中 IF 列中的值。

这是我尝试使用但不起作用的代码:

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

2 个答案:

答案 0 :(得分:2)

这是你在尝试的吗?

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

答案 1 :(得分:0)

SO上有一个similar problem,但我提出了一个不同的VBA解决方案。它将根据该列的标题更改列的数字格式(标题行除外)。

要手动执行此操作,您可以选择“格式化单元格”的“自定义”类别,然后输入

"Location: "General;"Location: "@

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

代码修改了Siddharth的 - 谢谢,先生 - (我没有明确声明所有变量,但这是最佳做法)。

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
相关问题