VBA – dynamic列名 – 转换为Cells.Value

在我的vbamacros中,我有下面的代码遍历每一行,并find一个特定的列,如果该行中的值=“UNGRADED”,做一些事情…

FinalRow = Cells(Rows.Count, 1).End(xlUp).Row 'Find the final row. For x = 1 To FinalRow 'Iterate through the rows gradedColumn = Cells(x, 14).Value ' Find the value for the row in column N. If gradedColumn = "UNGRADED" Then 'Do something... 

我现在试图修改这个段落来dynamic地按名称来search列标题,标题是“GRADED / UNGRADED”。

  Dim gradedColumn As Range FinalRow = Cells(Rows.Count, 1).End(xlUp).Row 'Find the final row. For x = 1 To FinalRow 'Iterate through the rows Set gradedColumn = Range( _ Range("A1:S1").Find("Graded / Ungraded").Offset(1), _ Range("A1:S1").Find("Graded / Ungraded").Offset(1).End(xlDown)) 'Find the column "Graded / Ungraded". If gradedColumn = "UNGRADED" Then 'Do something... 

目前,这段文字不起作用,收到13种types的不匹配错误。 设置gradedColumnvariables时,我认为.Value函数需要放置在某处,但我不确定如何继续。

根据答案更新。 我已经修改了我的代码,现在似乎正在工作。

  Set gradedColumn = Range( _ Range("A1:S1").Find("Graded / Un").Offset(1), _ Range("A1:S1").Find("Graded / Un").Offset(1).End(xlDown)) x = 2 For Each mycell In gradedColumn If mycell = "UNGRADED" Then Cells(x, 5).Resize(1, 6).Copy Sheets("SicknessRecordUngraded").Select NextRow = Cells(Rows.Count, 1).End(xlUp).Row +1 Cells(NextRow, 1).Select ' Find the next row. Selection.PasteSpecial Paste:=xlValues, Operation:=xlNone, SkipBlanks:= _ False, Transpose:=False Sheets("SicknessRecord").Select End If x = x + 1 Next mycell 

我并不完全清楚你想要怎么处理你的范围,但是我认为这个代码足以让你继续进行下去,这将给你的单元格地址提供GRADED / UNGRADED标题,格式为“ $ C $ 1“,如果您需要/希望,您可以将其传入范围。

 Dim gradedColumn As Range FinalRow = Cells(Rows.Count, 1).End(xlUp).Row 'Find the final row. For x = 1 To FinalRow 'Iterate through the rows titleCell = Range("A1:S1").Find("Graded / Ungraded").Address lastCellInGradedColum = Range("A1:S1").Find("Graded / Ungraded").End(xlDown).Address ' do something Next x 'alternatively, iterate through the cells in your range like this: Set gradedColumn = Range( _ Range("A1:S1").Find("Graded / Ungraded").Offset(1), _ Range("A1:S1").Find("Graded / Ungraded").Offset(1).End(xlDown)) For Each mycell In gradedColumn If mycell = "UNGRADED" Then 'Do something... End If Next mycell