类型不匹配错误Excel VBA - 循环使用已使用范围的每一列

时间:2013-10-15 18:02:25

标签: excel vba excel-vba

我有一个excel电子表格,顶部有一个标题行。我正在尝试记录我的Excel电子表格(标题行)顶行中每个单元格的列号,这些列号与某个字符串匹配,例如"推荐的操作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是行和列的总数(分别在电子表格中)。

我一直收到' Type Mismatch'错误:

If c.Value = "Recommended Action 1" Then

在此错误期间,我将光标放在c值上,然后出现错误2023'消息。

我怀疑是因为c是列号,而不是实际的范围地址。我认为这个错误是由于我不知道什么类型的变量' c'实际上正在返回 - 我认为这是一个范围对象。

1 个答案:

答案 0 :(得分:1)

我认为这是你在尝试的?

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