2013-10-15 45 views
1

我有一個excel電子表格,頂部有一個標題行。我試圖登錄我的Excel電子表格(標題行)的首行中每個單元格的列數,某字符串匹配,如「建議操作1」類型不匹配錯誤Excel VBA - 循環使用已用範圍的每列

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'實際返回 - 我認爲它是一個範圍對象。

+0

您是否想知道第1行有哪些列有'推薦的操作1','推薦的操作2'和'推薦的操作3'? –

+0

'錯誤2023'是一個'#Ref!'錯誤。嘗試'如果CStr(c.Value)...' –

回答

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 
+0

這可以工作,但列號會將單元格移到右側。 – H3lue

+0

對不起,我沒有得到你。 –

+0

正在返回的列數比應該大的+1。正如函數GetCol認爲這些值在電子表格的右邊是1。 – H3lue