带有跟随函数的语句

时间:2019-06-12 17:24:13

标签: excel vba

我正在根据Internet的建议将代码从使用.active和.select切换到更可靠的方式。我想知道with语句的功能,以及它们是否遵循已创建的功能。

'---Which way is more proper? 
'1.
Sub TestCase()
  With ThisWorkbook.Worksheets("TestWorksheet")
    TestFunction()
  End With
End Sub

Function TestFunction()As Integer
  Dim I As Integer
  I = .cells(1,1)
End function
'--2.
Sub TestCase()
  With ThisWorkbook.Worksheets("TestWorksheet")
    TestFunction()
  End With
End Sub

Function TestFunction()As Integer
  Dim I As Integer
  With ThisWorkbook.Worksheets("TestWorksheet")
    I = .cells(1,1)
  End With 
End function

2 个答案:

答案 0 :(得分:3)

不幸的是,With语句不跟随被调用函数。对于该功能,您需要将参数传递给该函数。这是一个以有效方式复制您提供的伪代码的示例:

Sub TestCase()

    MsgBox TestFunction(ThisWorkbook.Worksheets("TestWorksheet"))

End Sub

Function TestFunction(ByRef ws As Worksheet) As Double

    With ws
        TestFunction = Val(.Cells(1, 1).Value)
    End With

End Function

请注意,Sub正在调用Function并传递作为工作表对象的参数。然后,您可以在函数中对传递的参数使用With语句。

答案 1 :(得分:2)

最合适(基于@BigBen的非常正确的评论):

Sub TestCase()  
    'Integer variable to catch the return of the function
    Dim somVar as Integer

    'Call the function, pass the worksheet. 
    somVar = TestFunction(ThisWorkbook.Worksheets("TestWorksheet"))  

    'Do something with the return
    Debug.print somVar
End Sub

Function TestFunction(ws as Worksheet) As Integer
  Dim I As Integer  
  I = ws.cells(1,1) 

  'Return the integer to the caller 
  TestFunction = I
End function