通过列名引用单元格

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

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

使用Cells(StartRow, 1)引用Cells(StartRow, 1)其中StartRow是一个预先声明和预定义的整数variables,用于指定行,“ 1 ”表示列。

编辑:现在,我想要更改此代码,而不是引用列标题

例如,一列的标题是:“Fab时间date”,我该如何参考?

是的,您可以简单地在引号中使用列的字母名称:

 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 

这里有两个不同的function来获得你想要的。 要使用它们,你必须把它们放在你的代码中。

 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) 
 ProductionWorkBook.Sheets("Production Schedule").Range("A" & StartRow).Value = EstJobName(i) 

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

 ProductionWorkBook.Sheets(“Production Schedule”)。Range(“E”&StartRow).Value = ...

会做这项工作。

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

 ProductionWorkBook.Sheets(“Production Schedule”)。Range(“StartCell”)。Offset(StartRow-1).Value

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