我有一个带有预定义列标题的Excel。问题是这些列标题可以位于每个迭代的任何位置,只有列标题是固定的而不是它们的位置(索引)。因此,我需要根据列名获取列索引以进行进一步处理。
答案 0 :(得分:0)
使用.Find()
找到包含您要查找的列的单元格。
我编写了以下示例,以在指定的行号上的某个列中添加值。您可能希望更改代码,以便将值添加到现有值的底部。为简单起见,下面的代码将找到列,向下到指定的行并将值更改为调用者指定的值。
Sub Macro1()
Dim result As Boolean
result = add_value_to_column("age", atRow:=3, newValue:=17)
'was that successful?
If result = True Then
MsgBox "value was added"
Else
MsgBox "value NOT added. maybe column does not exist"
End If
End Sub
Function add_value_to_column(col_name As String, _
atRow As Integer, _
newValue As String) As Boolean
Dim c As Range
'Assuming the header row is the first row at the top (1:1)
With Range("1:1")
'try to find the column specified in the function parameters
Set c = .Find(col_name, LookIn:=xlValues)
'If the column was found then it will not be nothing
'NOT NOTHING = THING :)
If Not c Is Nothing Then
'access the row specified in the parameter, at the column,
'and set the value for that location
Cells(atRow, c.Column).Value = newValue
'Optioal: inform the caller that the value was set
add_value_to_column = True
Else
'optional: inform the caller that column was not found
add_value_to_column = False
End If
End With
End Function
这是显示样本数据集的图像。运行上面的代码已将值17
添加到行号age
的{{1}}列
答案 1 :(得分:0)
我找到了问题中描述的另一种访问列的方法,所以我应该相应地更改我的第一个答案。但我想也许这个答案适用于其他情况。
以下是获取包含值的列的更快捷方法:
Sub Macro1()
ColumnByValue("age").Offset(5, 0).Value = "17"
End Sub
Function ColumnByValue(col As String) As Range
Set ColumnByValue = Range("1:1").Find(col)
End Function