Excel VBA:连接函数中的引用表头#

时间:2018-04-05 15:14:10

标签: excel vba excel-vba

我正在尝试将一个列(7)添加到表中,并使用列(6)和(5)的CONCATENATE填充该列中的单元格

我可以通过使用标题名称使其工作,但是想要使用列号。关于如何使这项工作的任何建议?

这就是我所拥有的:

Sub AddColAndName(ws As Worksheet, tbl As ListObject, newColPos As Long, newColName As String, conColPos1 As Long, conColPos2 As Long)

    With tbl
        .ListColumns.Add newColPos
        .HeaderRowRange(newColPos) = newColName
        .ListColumns(newColPos).DataBodyRange.FormulaR1C1 = "=CONCATENATE([@FinancialMonthNumberNameShort],[@FinancialYear])"
    End With

    With ws
        .Columns(newColPos).EntireColumn.AutoFit
    End With

End Sub

我想将[@FinancialMonthNameShort]更改为作为参数传递的数字(conColPos1)..或者我可以使用传递给Sub的参数的任何其他方式。

谢谢大家的帮助。

// JATE

1 个答案:

答案 0 :(得分:0)

喜欢这个

Option Explicit

Public Sub test()

    Dim tbl As ListObject
    Dim ws As Worksheet
    Set ws = ThisWorkbook.Worksheets("Sheet17") 'change as required
    Set tbl = ws.ListObjects("Table5") 'change as required

    Dim newColPos As Long
    Dim conColPos1 As Long
    Dim conColPos2 As Long

    If conColPos1  > tbl.Range.Columns.Count  Or conColPos2 > tbl.Range.Columns.Count Then
        MsgBox "Invalid columns for concatenation"
        End
    End If

    conColPos1 = 2
    conColPos2 = 3
    newColPos = 4

    Dim newColName As String
    newColName = "NewColumn"

    AddColAndName ws, tbl, newColPos, newColName, conColPos1, conColPos2

End Sub

Public Sub AddColAndName(ByVal ws As Worksheet,ByVal tbl As ListObject, ByVal newColPos As Long,ByVal newColName As String,ByVal conColPos1 As Long, ByVal conColPos2 As Long)

    With tbl

        If newColPos > .Range.Columns.Count Then
            .ListColumns.Add .Range.Columns.Count + 1
        Else
            .Add newColPos
        End If

        .HeaderRowRange(newColPos) = newColName
        .ListColumns(newColPos).DataBodyRange.Formula = "=CONCATENATE([@" & .HeaderRowRange(conColPos1) & "],[@" & .HeaderRowRange(conColPos2) & "])"

    End With
    With ws
        .Columns(newColPos).EntireColumn.AutoFit
    End With

End Sub

您也可以使用:

.ListColumns(newColPos).DataBodyRange.Formula = "=CONCATENATE([@" & .ListColumns(conColPos1).Cells(1, 1) & "],[@" & .ListColumns(conColPos2).Cells(1, 1) & "])"