如何按列名引用表中的新单元格

时间:2015-04-28 16:50:36

标签: excel-vba vba excel

我有一个工作子例程,它将一个值插入一个单元格,作为表格新行的一部分。我引用单元格以按列号插入数据。但是,我希望能够使用表中的列/标题名称,而不是数字,以便可以移动表列而不会破坏宏中的单元格引用。有谁知道怎么做?

这是我的示例代码。

Sub InsertValue(ByRef iTargetCell As Integer, ByRef CellData As String, ByRef strType As String)

  Select Case strType
    ' Define the data as Text
      Case "T"
      ' Specify the number format to be used for a particular column in the new row
        NewRow.Range.Cells(1, iTargetCell).NumberFormat = "@"
      ' Insert the data for a particular column into the new row
        NewRow.Range.Cells(1, iTargetCell).Value = CellData
    ' Define the data as a number
      Case "N"
        NewRow.Range.Cells(1, iTargetCell).NumberFormat = "0"
        NewRow.Range.Cells(1, iTargetCell).Value = CellData
  End Select
End Sub

变量NewRow已经公开定义。

Public NewRow As ListRow

它设置在另一个子程序中。

Set NewRow = Range(strTableName).ListObject.ListRows.Add(AlwaysInsert:=True)

1 个答案:

答案 0 :(得分:1)

ActiveSheet.ListObjects("Table1").ListColumns("ColName").Index

将返回带有标题" ColName"的列的位置。在表格中

相关问题