我正在尝试创建一个新列,该列使用其他两个列中的条件进行输出。现在,我收到类型不匹配错误。在此之前,我的输出根本没有输出。
Sub FormatcolumnF()
Dim eqa As Range, eqt As Range, rngResult As Range
Dim arr_a As Variant, arr_t As Variant
Dim wks As Worksheet, i As Integer
Dim lngLastRow As Long
Set wks = ActiveSheet
'or even better by name like "Worksheets(Table1)"
With wks
'Now that the Worksheet is defined, we'll find the last row number
lngLastRow = .Cells.Find(What:="*", LookIn:=xlFormulas, _
SearchOrder:=xlByRows, _
SearchDirection:=xlPrevious).Row
'We can now use a Range to grab all the category data
Set eqa = .Range(.Cells(2, 4), .Cells(lngLastRow, 1))
Set eqt = .Range(.Cells(2, 3), .Cells(lngLastRow, 1))
End With
arr_a = eqa
arr_t = eqt
Dim result As String
For i = LBound(arr_a, 1) To UBound(arr_a, 1)
If arr_a(i, 1) >= arr_t(i, 1) - 0.025 _
Or arr_a(i, 1) <= arr_t(i, 1) + 0.025 Then
result = "ON TARGET"
ElseIf arr_a(i, 1) <= arr_t(i, 1) - 0.025 Then
result = "UNDER"
ElseIf arr_a(i, 1) >= arr_t(i, 1) + 0.025 Then
result = "OVER"
End If
Next i
With wks
Set rngResult = .Range(.Cells(2, 6), .Cells(lngLastRow, 1))
.Cells(1, 6) = "OVER/UNDER"
End With
End Sub
我需要在工作表的第6列中反映出基于我为第3列和第4列创建的循环的输出字符串。我的行数可变。
答案 0 :(得分:2)
有很多小事情,例如范围旁边的Cells
引用上的列不匹配。
但是主要的问题是在将输出分配给变量之后,您对输出不执行任何操作。使该变量成为数组,然后将该数组分配给范围。
还要测试这些值,以确保它们首先不是错误(类型不匹配的最可能原因)或不是数值(第二可能的原因)。
Sub FormatcolumnF()
Dim rngResult As Range
Dim arr_a As Variant, arr_t As Variant
Dim wks As Worksheet, i As Long
Dim lngLastRow As Long
Set wks = ActiveSheet
'or even better by name like "Worksheets(Table1)"
With wks
'Now that the Worksheet is defined, we'll find the last row number
lngLastRow = .Cells.Find(What:="*", LookIn:=xlFormulas, _
SearchOrder:=xlByRows, _
SearchDirection:=xlPrevious).Row
'We can now use a Range to grab all the category data
'Skip setting ranges and assign directly to the arrays
arr_a = .Range(.Cells(2, 4), .Cells(lngLastRow, 4)) 'the 1 is column A it should match the 4
arr_t = .Range(.Cells(2, 3), .Cells(lngLastRow, 3)) 'the 1 is column A it should match the 3
'Create an array for the output
Dim result() As Variant
ReDim result(1 To UBound(arr_a, 1), 1 To 1) As Variant
For i = LBound(arr_a, 1) To UBound(arr_a, 1)
'make sure both arr_a and arr_t are not error and numeric
If Not IsError(arr_a(i, 1)) And Not IsError(arr_t(i, 1)) Then
If IsNumeric(arr_a(i, 1)) And IsNumeric(arr_t(i, 1)) Then
'Load the output in the array
' Should be And not Or
If arr_a(i, 1) >= arr_t(i, 1) - 0.025 _
And arr_a(i, 1) <= arr_t(i, 1) + 0.025 Then
result(i, 1) = "ON TARGET"
ElseIf arr_a(i, 1) <= arr_t(i, 1) - 0.025 Then
result(i, 1) = "UNDER"
ElseIf arr_a(i, 1) >= arr_t(i, 1) + 0.025 Then
result(i, 1) = "OVER"
End If
Else
result(i, 1) = "Not Numeric"
End If
Else
result(i, 1) = "Error"
End If
Next i
'load the output array into the cells
.Range(.Cells(2, 6), .Cells(lngLastRow, 6)) = result
.Cells(1, 6) = "OVER/UNDER"
End With
End Sub