-2

可能重复:
excel 宏:ByRef 参数类型不匹配

我写了如下代码:

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(...) 来调用,但是在我测试后它有错误。

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 

如何修改它?我真的需要一些建议。thx

4

1 回答 1

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 函数已经完成了您想要的操作...

于 2012-09-20T18:04:11.757 回答