VBA循环遍历列 - 如果内部为

时间:2011-01-31 13:26:15

标签: excel vba excel-vba

这段代码有什么问题?它应该返回它找到“1”的列的标题(第1行)。我传递行号(nr),它应该在列M和T(包括)之间查看

Function who(ByVal rowNr As Integer) As String
    Dim temp As String
    Dim ws As Worksheet
    With ActiveSheet
        Set ws = ActiveWorkbook.Sheets(.Name)
    End With
    For i = 13 To 20 Step 1
        If ws.Cells(i, rowNr).Value = 1 Then
            temp = temp & " " & ws.Cells(i,1).Value
        End If
    Next i
    who = temp
End Function

我得到的错误是

  

应用程序定义或对象定义   错误

并标记行

If ws.Cells(i, nr).Value = 1 Then

我真的不喜欢VB。

2 个答案:

答案 0 :(得分:1)

如果nr用作数值,为什么要将其作为String发送。尝试将其更改为Integer,至少应该更进一步。

编辑:我忘记了我认为你可能也混淆了行/列。我想也许你想要它:

If ws.Cells(nr, i).Value = 1 Then

答案 1 :(得分:0)

这对我有用

Function who(ByVal rowNr As Long) As String
    Dim temp As String
    Dim ws As Worksheet
    Dim i As Long

    Set ws = ActiveSheet

    For i = 13 To 20 Step 1
        If ws.Cells(rowNr, i).Value = 1 Then
            temp = temp & " " & ws.Cells(1, i).Value
        End If
    Next i

    who = Trim(temp)

End Function