我写了如下代码:
For xx = 1 To 100
For yy = 1 To 100
strTemp = Worksheets("APM Output").Cells(xx, yy).Value
If InStr(strTemp, ">> State Scalars") <> 0 Then
GoTo label1
End If
Next
Next
label1:
For uu = 1 To 100
For vv = 1 To 100
strTemp = Worksheets("APM Output").Cells(uu, vv).Value
If InStr(strTemp, ">> GPU LPML") <> 0 Then
GoTo label2
End If
Next
Next
label2:
For mm = 1 To 100
For nn = 1 To 100
strTemp = Worksheets("APM Output").Cells(mm, nn).Value
If InStr(strTemp, ">> Limits and Equations") <> 0 Then
GoTo label3
End If
Next
Next
....
我想把它们总结成一个新的子(...)来调用,但是在我测试之后它有错误。
Sub search(row As Variant, col As Variant, wkst As String, str As String, label_num As Name)
For row = 1 To 100
For col = 1 To 100
strTemp = Worksheets(wkst).Cells(row, col).Value
If InStr(strTemp, str) <> 0 Then
GoTo label_num
End If
Next
Next
End Sub
如何修改?我真的需要一些建议。谢谢
答案 0 :(得分:1)
在一个单独的函数中分割sub的循环部分是一个很好的编程习惯
我个人会进入以下路线:
Sub Subroutine()
set tCell = UDF_FindValue("APM Output",">> State Scalars")
set tCell = UDF_FindValue("APM Output",">> GPU LPML")
set tCell = UDF_FindValue("APM Output",">> Limits and Equations")
End Sub
Function UDF_FindValue(WS_Name as String, SearchString as String) as Range
Set RefWS = WorkSheets(WS_Name)
for each sCell in intersect(RefWS.Rows("1:100"),RefWS.Columns("1:100"))
if sCell.value = SearchString then
Set UDF_FindValue = sCell
End function
end if
next sCell
End Function
如果你的功能足够通用,你也可以在以后重新使用它......
它还可以让您轻松修改代码,例如,如果您发现find函数已经执行了您想要的操作...