3

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

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

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

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

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

4

4 回答 4

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
于 2013-01-25T14:46:00.397 回答
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)
于 2013-01-25T15:40:59.483 回答
1
ProductionWorkBook.Sheets("Production Schedule").Range("A" & StartRow).Value = EstJobName(i)

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

于 2013-01-25T14:46:10.043 回答
0
ProductionWorkBook.Sheets("生产计划").Range("E"& StartRow).Value = ...

将完成这项工作。

但请记住,使用像列字母这样的硬编码引用会冒着在编辑工作表时宏中断的风险(例如插入一列)。因此,最好使用命名范围并Offset访问:

ProductionWorkBook.Sheets("生产计划").Range("StartCell").Offset(StartRow-1).Value

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

于 2013-01-25T14:46:31.340 回答