types不匹配错误Excel VBA – 遍历已使用范围的每一列

我有一个顶部的标题行的Excel电子表格。 我试图logging在我的Excel电子表格(标题行),匹配一个特定的string,如“推荐的行动1”的第一行的每个单元格的列号

For Each c In Worksheets("Cost Estimates").Range(Cells(1, 1), Cells(totalRows, totalCols)) If c.Value = "Recommended Action 1" Then recAct1 = c.Column Debug.Print CStr(recAct1) ElseIf c.Value = "Recommended Action 2" Then recAct2 = c.Column ElseIf c.Value = "Recommended Action 3" Then recAct3 = c.Column End If Next 

其中recAct包含列号,totalRows和totalCols是行和列的总数(分别在电子表格中)。

我不断收到“types不匹配”错误:

 If c.Value = "Recommended Action 1" Then 

在这个错误期间,我将光标置于c值上,并收到“错误2023”消息。

我怀疑这是因为c是列号而不是实际的范围地址。 我认为这个错误是由于我不知道什么types的variables'c'实际返回的事实 – 我认为这是一个范围对象。

我想这是你正在尝试的?

 Option Explicit Sub Build_Formulas_v2() Dim RAOneCol As Long, RATwoCol As Long, RAThreeCol As Long RAOneCol = GetCol("Recommended Action 1") RATwoCol = GetCol("Recommended Action 2") RAThreeCol = GetCol("Recommended Action 3") If RAOneCol <> 0 Then _ MsgBox "Recommended Action 1 found in column " & RAOneCol Else _ MsgBox "Recommended Action 1 not found" If RATwoCol <> 0 Then _ MsgBox "Recommended Action 2 found in column " & RATwoCol Else _ MsgBox "Recommended Action 2 not found" If RAThreeCol <> 0 Then _ MsgBox "Recommended Action 3 found in column " & RAThreeCol Else _ MsgBox "Recommended Action 3 not found" End Sub Function GetCol(sString As String) As Long Dim aCell As Range Dim ws As Worksheet Set ws = ThisWorkbook.Sheets("Cost Estimates") Set aCell = ws.Rows(1).Find(What:=sString, LookIn:=xlValues, _ LookAt:=xlWhole, SearchOrder:=xlByRows, SearchDirection:=xlNext, _ MatchCase:=False, SearchFormat:=False) If Not aCell Is Nothing Then GetCol = aCell.Column End If End Function