VBA 循环遍历列 - 如果在 for
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4851353/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
VBA loop through columns - if inside for
提问by SuperMario
What is wrong with this code? It is supposed to return header (1st row) of a column in which it finds "1". I pass the row number (nr) and it is supposed to look between columns M and T (inclusive)
这段代码有什么问题?它应该返回找到“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
The error I get is
我得到的错误是
Application-Defined or Object-Defined error
应用程序定义或对象定义错误
And marks line
并标记线
If ws.Cells(i, nr).Value = 1 Then
I truly dislike VB.
我真的不喜欢VB。
采纳答案by Hans Olsson
If nr
is used as a numerical value, why are you sending it in as a String
. Try changing that to an Integer
and you should be a bit further along at least.
如果nr
用作数值,为什么要将其作为String
. 尝试将其更改为 an Integer
,您至少应该更进一步。
Edit: I forgot that I think you might have mixed up rows/columns as well. I think maybe you want it to be:
编辑:我忘了我认为您可能也混淆了行/列。我想也许你希望它是:
If ws.Cells(nr, i).Value = 1 Then
回答by Dick Kusleika
This worked for me
这对我有用
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