Visual Basic Max函数抛出1004错误

时间:2016-08-25 13:51:44

标签: vba excel-vba excel

我有2个表"有目的样本"和"缩放"。这个宏是为缩放编写的。

现在,当我运行这个时,它会在 rowMax = Application.WorksheetFunction.Max(Range(src.Cells(curRow,11),src.Cells(curRow,37)))抛出1004
给定范围内的某些单元格也是字符串。很少有人也是#N / A.

VB中的Noob。真的很感激任何帮助。

Sub stdInScaled()

Dim curCol, curRow
curRow = 2

Dim src As Worksheet
Set src = Worksheets("PurposefulSample")

Do While (src.Cells(curRow, 1).Value <> "")
curCol = 11

    Do While (CStr(src.Cells(curRow, curCol).Value) <> "")
        If (IsNumeric(src.Cells(curRow, curCol).Value)) Then
            Dim rowMax
            rowMax = Application.WorksheetFunction.Max(Range(src.Cells(curRow, 11), src.Cells(curRow, 37)))
            If (rowMax > 1) Then
                Cells(curRow, curCol).Value = 100 * CLng(src.Cells(curRow, curCol).Value) / rowMax
            Else
                Cells(curRow, curCol).Value = "No Business"
            End If
        Else
            Cells(curRow, curCol).Value = "Data NA"
        End If
        curCol = curCol + 1
    Loop

    curRow = curRow + 1
Loop

End Sub

1 个答案:

答案 0 :(得分:1)

两件事:

  1. 最好是对所有范围对象的父母进行限定,以确保不会混淆哪个单元被引用。

  2. 如果数据存在错误,则需要使用数组公式Max来跳过错误。同样在公式上让我们将它向上移动一个循环,这样它就不会在每一列重新计算相同的答案。

  3. 代码:

    Sub stdInScaled()
    
    Dim curCol, curRow
    curRow = 2
    
    Dim src As Worksheet
    Set src = Worksheets("PurposefulSample")
    
    Dim trgt As Worksheet
    Set trgt = Worksheets("scaled")
    
    Do While (src.Cells(curRow, 1).Value <> "")
        curCol = 11
        Dim rowMax
        Dim rng As String: rng = src.Range(src.Cells(curRow, 11), src.Cells(curRow, 37)).Address
        rowMax = src.Evaluate("Max(IF(isnumber(" & rng & ")," & rng & "))")
        Do While (CStr(src.Cells(curRow, curCol).Value) <> "")
            If (IsNumeric(src.Cells(curRow, curCol).Value)) Then
                If (rowMax > 1) Then
                    trgt.Cells(curRow, curCol).Value = 100 * CLng(src.Cells(curRow, curCol).Value) / rowMax
                Else
                    trgt.Cells(curRow, curCol).Value = "No Business"
                End If
            Else
                trgt.Cells(curRow, curCol).Value = "Data NA"
            End If
            curCol = curCol + 1
        Loop
        curRow = curRow + 1
    Loop
    
    End Sub