专家!
我正在尝试自动化手动过程,并且遇到(我确定)一个简单的修复。大约有8列可能包含我需要复制到B列的索引/匹配公式的结果。例如,列'A'是IP地址,列'B'需要有一个值列“C”到“K”。逻辑需要首先查看'K'然后向'C'移动,检查该值是否是第一个错误(如#N / A或0)。如果不存在错误,则将该值复制到摘要表中。我认为我的真正障碍是我无法获得检查错误的逻辑。它要么什么都不做(我怀疑我只是退出循环),或者它只是复制一切,无论如何。非常感谢帮助!
Sub MakeSummary()
Dim oRng1 As Range, oRng2 As Range
Dim oWS1 As Worksheet, oWS2 As Worksheet, i As Long
' Initial cell to check
Set oWS1 = ThisWorkbook.Worksheets("Master")
Set oRng1 = oWS1.Range("A1")
' Initial cell to store
Set oWS2 = ThisWorkbook.Worksheets("Summary")
Set oRng2 = oWS2.Range("A1")
' Clear original data on Summary
i = 0
Do Until IsEmpty(oRng2.Offset(i, 0))
oRng2.Offset(i, 0).EntireRow.ClearContents
i = i + 1
Loop
' Look for IPs on "Master", then put in to "Summary"
' If value in cell is #N/A or 0, then skip to next cell
Do Until IsEmpty(oRng1)
If oRng1.Value = Application.WorksheetFunction.IsNA(oRng1.Formula) Then
Set oRng2 = oRng2.Offset(0, 1)
Else
oRng2.Value = oRng1.Offset(0, 1).Value ' IPs
oRng2.Offset(0, 1).Value = oRng1.Offset(0, 2).Value ' 1st Match
oRng2.Offset(0, 2).Value = oRng1.Offset(0, 3).Value ' 2nd Match
Set oRng2 = oRng2.Offset(1, 0) ' Move to next row to store
Set oRng1 = oRng1.Offset(1, 0) ' Move to next row to check
Loop
' Clean up
Set oRng1 = Nothing
Set oWS1 = Nothing
Set oRng2 = Nothing
Set oWS2 = Nothing
End Sub
答案 0 :(得分:1)
您可以使用Application.WorksheetFunction.IsError
检查公式结果,看是否是错误。在这种情况下,您的代码将如下所示(编辑后使用评论中提到的IsError()
函数
Sub MakeSummary2()
Dim oRng1 As Range
Dim oRng2 As Range
Dim oWS1 As Worksheet
Dim oWS2 As Worksheet
Dim X As Integer
' Initial cell to check
Set oWS1 = ThisWorkbook.Worksheets("Master")
Set oRng1 = oWS1.Range("A2")
' Initial cell to store
Set oWS2 = ThisWorkbook.Worksheets("Summary")
Set oRng2 = oWS2.Range("A2")
' Clear original data on Summary
oWS2.Cells.Clear
' Look for IPs on "Master", then put in to "Summary"
' If value in cell is #N/A or 0, then skip to next cell
Do Until IsEmpty(oRng1)
If IsError(oRng1.Offset(0, 1).Value) Then
For X = 10 To 2 Step -1
If Not IsError(oRng1.Offset(0, X).Value) Then
If oRng1.Offset(0, X).Value <> "" Or oRng1.Offset(0, X).Value <> 0 Then
oRng2.Value = oRng1.Value
oRng2.Offset(0, 1).Value = oRng1.Offset(0, X).Value
Set oRng2 = oRng2.Offset(1, 0)
Exit For
End If
End If
Next X
If X = 1 And oRng2.Value = "" Then
oRng2.Value = oRng1.Value
oRng2.Offset(0, 1).Value = "No Data"
Set oRng2 = oRng2.Offset(1, 0)
End If
Else
oRng2.Value = oRng1.Value
oRng2.Offset(0, 1).Value = oRng1.Offset(0, X).Value
Set oRng2 = oRng2.Offset(1, 0)
End If
Set oRng1 = oRng1.Offset(1, 0) ' Move to next row to check
Loop
End Sub
这将放置&#34; No Data&#34;的值。在B列中,如果C:K列中的所有数据都是错误,空或0