简体   繁体   中英

excel VBA For each loop for range error #VALUE

I have used for each loop through my defined function in excel VBA but the function output is #VALUE. I think the error is inside my loop that is as follow:

Thank you guys for comments. My function code is as follow that I have corrected the original one I sent :

Public Function MaxWindDir(warr As Range) As Integer
Dim WindDir() As Integer
Dim maxwindsp As Integer
Dim wcell As Range
Dim i As Integer
Dim MaxDir As Integer
i = 0
maxwindsp = Application.Max(warr)
For Each wcell In warr
    If wcell.Value = maxwindsp Then
        WindDir(i) = Range("J" & wcell.Row).Value
        i = i + 1
    End If
Next wcell
If i = 1 Then
    MaxWindDir = WindDir(0)
Else
    MaxDir = WindDir(0)
    For i = 0 To UBound(WindDir)
        If WindDir(i) >= MaxDir Then
            MaxDir = WindDir(i)
        End If
    Next i
    MaxWindDir = MaxDir
End If
End Function

Please help me out of this error.

The error is occurring because your WindDir array is undimensioned, so the lines WindDir(i)... will throw an error.

It's not great form to iteratively redimension an array within a loop, but the added ReDim Preserve line below in your code shows you what I mean:

For Each wcell In warr
    If wcell.Value = maxwindsp Then
        ReDim Preserve WindDir(i)
        WindDir(i) = Range("J" & wcell.Row).Value
        i = i + 1
    End If
Next wcell

Your post throws up a couple of other points too:

  1. Perhaps consider calling your UDFs from a module while you develop them. This way any errors will be more meaningfully displayed to you. If you run the following routine, calling your function as posted, the undimensioned array issue would be highlighted immediately:

     Public Sub RunMe() Dim r As Range Set r = Sheet1.Range("K2:K19") 'or whatever the range is Debug.Print MaxWindDir(r) End Sub 
  2. Why trouble yourself with the array at all? Given that you're accessing the WindDir values in the first loop, why not just check for the maximum there? This way, your entire function could simply be:

     Public Function MaxWindDir(warr As Range) As Long Dim wcell As Range Dim maxWindSpd As Long Dim windSpd As Long Dim windDir As Long maxWindSpd = Application.Max(warr) For Each wcell In warr.Cells windSpd = wcell.Value2 If windSpd = maxWindSpd Then windDir = warr.Worksheet.Cells(wcell.Row, "J").Value2 If windDir >= MaxWindDir Then MaxWindDir = windDir End If Next End Function 
  3. Note @Comitern's point about the Range qualifier (and my rather clumsy attempt at keeping faithful to your posted code whilst still qualifying the range).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM