1

我有一个顶部有标题行的 Excel 电子表格。我正在尝试记录与某个字符串(例如“推荐操作 1”)匹配的 Excel 电子表格顶行(标题行)中每个单元格的列号

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 是行和列的总数(分别在电子表格上)。

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

If c.Value = "Recommended Action 1" Then

在此错误期间,我将光标放在 c 值上,并收到“错误 2023”消息。

我怀疑这是因为 c 是列号而不是实际范围地址。我认为这个错误是由于我不知道实际返回的是什么类型的变量“c”——我认为它是一个范围对象。

4

1 回答 1

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
于 2013-10-15T18:15:21.847 回答