在VBA中重构 - 将代码移动到函数中不起作用

时间:2012-09-07 07:17:00

标签: vba excel-vba refactoring excel

我对VBA Excel相当新。我试图通过在函数中插入代码块然后调用函数而不是块来重构一些VBA宏。代码块在宏中多次复制粘贴(仅更改一个常量)。然而,旧的解决方案可行,而具有功能的新解决方案则不然。它甚至不会抛出错误消息,它只是冻结整个Excel应用程序。你碰巧知道我可能做错了吗?

编辑:如果有任何不同,将从SAP调用宏。

OLD:

Dim tbl As Object
If ThisWorkbook.Container.LinkServer.Items("ITEMS").Table Is Nothing Then
  Exit Sub
Else
  Set tbl = ThisWorkbook.Container.LinkServer.Items("ITEMS").Table
  maxNumRow = ThisWorkbook.Container.LinkServer.Items("ITEMS").Table.rowCount
  '... (do stuff)

Dim tbl As Object
If LinkServer_Table("ITEMS", tbl, maxNumRow) = True Then
  '... (do stuff)

...
Function LinkServer_Table( _
  ByVal name As String, _
  ByRef tbl As Object, _
  Optional ByRef rowCount As Long)

  If ThisWorkbook.Container.LinkServer.Items(name).Table Is Nothing Then
    LinkServer_Table = False
  Else
    Set tbl = ThisWorkbook.Container.LinkServer.Items(name).Table
    rowCount = ThisWorkbook.Container.LinkServer.Items(name).Table.rowCount
    LinkServer_Table = True
  End If
End Function

2 个答案:

答案 0 :(得分:2)

Treb 指出“name”参数中存在问题后,我专注于它并且经过一些试错后我带来了下面的工作版本。我仍然不太了解发生了什么,但它正在发挥作用。

Function LinkServer_Table( _
  ByVal name As String, _
  ByRef tbl As Object, _
  Optional ByRef maxRows As Long)

    If ThisWorkbook.Container.LinkServer.Items(CVar(name)).Table Is Nothing Then
        LinkServer_Table = False
    Else
        Set tbl = ThisWorkbook.Container.LinkServer.Items(CVar(name)).Table
        maxRows = ThisWorkbook.Container.LinkServer.Items(CVar(name)).Table.RowCount
        LinkServer_Table = True
    End If
End Function

然而,我也非常重视 Jean-FrançoisCorbett的输入,并尝试以更清洁的方式重构代码。最后,我意识到代码可以直接重写为非常简短和可读的块:

Dim tbl As Object        
Set tbl = ThisWorkbook.Container.LinkServer.Items("ITEMS").Table
If Not tbl Is Nothing Then
  maxNumRow = tbl.RowCount
  '...(do stuff)

感谢两位大家的意见。

答案 1 :(得分:0)

您需要定义函数的返回类型:

Function LinkServer_Table( _
  ByVal name As String, _
  ByRef tbl As Object, _
  Optional ByRef rowCount As Long) As Boolean