通过列名引用单元格

时间:2013-01-25 14:41:31

标签: excel vba

我想更新工作簿中单元格的内容。我的代码看起来有点像这样:

ProductionWorkBook.Sheets("Production Schedule").Cells(StartRow, 1).Value = EstJobName(i)

使用Cells(StartRow, 1)引用单元格其中StartRow是预先声明的预定义整数变量,用于指定行,“1”表示列。

编辑: 现在,我想更改此代码以通过列HEADERS 引用列。

例如,列的标题是:“Fab Hours Date”,我该如何引用它?

4 个答案:

答案 0 :(得分:3)

是的,您只需使用引号中列的字母名称:

Cells(StartRow, "A")

编辑回答你的进一步问题: 要查找特定的列名称,请尝试以下操作:

columnNamesRow = 1           ' or whichever row your names are in
nameToSearch = "Fab Hours"   ' or whatever name you want to search for
columnToUse = 0
lastUsedColumn = Worksheets("Foo").Cells(1, Worksheets("Foo").Columns.Count).End(xlToLeft).Column

For col = 1 To lastUsedColumn
   If Worksheets("Foo").Cells(columnNamesRow, col).Value = nameToSearch Then
      columnToUse = col
   End If
Next col


If columnToUse > 0 Then
' found the column you wanted, do your thing here using "columnToUse" as the column index
End If

答案 1 :(得分:2)

以下是两种不同的功能,可以满足您的需求。要使用它们,您必须将它们放入代码中。

Function ColumnNumberByHeader(text As String, Optional headerRange As Range) As Long
    Dim foundRange As Range
    If (headerRange Is Nothing) Then
        Set headerRange = Range("1:1")
    End If

    Set foundRange = headerRange.Find(text)
    If (foundRange Is Nothing) Then
        MsgBox "Could not find column that matches header: " & text, vbCritical, "Header Not Found"
        ColumnNumberByHeader = 0
    Else
        ColumnNumberByHeader = foundRange.Column
    End If
End Function

Function ColumnNumberByHeader2(text As String, Optional headerRange As Range) As Long
    If (headerRange Is Nothing) Then
        Set headerRange = Range("1:1")
    End If
    On Error Resume Next
    ColumnNumberByHeader2 = WorksheetFunction.Match(text, headerRange, False)
    If Err.Number <> 0 Then
        MsgBox "Could not find column that matches header: " & text, vbCritical, "Header Not Found"
        ColumnNumberByHeader2 = 0
    End If
    On Error GoTo 0
End Function

示例呼叫:

 ColumnNumberByHeader ("Extn")
 ColumnNumberByHeader("1718", Range("2:2"))

或者在你的情况下:

ProductionWorkBook.Sheets("Production Schedule"). _
Cells(StartRow, ColumnNumberByHeader("Fab Hours Date")).Value = EstJobName(i)

答案 2 :(得分:1)

ProductionWorkBook.Sheets("Production Schedule").Range("A" & StartRow).Value = EstJobName(i)

除非您的意思是该列是您定义的命名范围?

答案 3 :(得分:0)

ProductionWorkBook.Sheets("Production Schedule").Range("E"& StartRow).Value = ...

将完成这项工作。

尽管请记住,使用像列字母这样的硬编码引用可能会在编辑工作表(例如插入列)时中断宏。因此,最好使用命名范围和Offset来访问:

ProductionWorkBook.Sheets("Production Schedule").Range("StartCell").Offset(StartRow-1).Value

现在您只需要为您的第一个单元格提供名称StartCell(确保它是名称管理器中的本地名称)