潜艇之间的VBA Pass值

时间:2017-10-02 04:23:49

标签: vba excel-vba function user-defined-functions excel

我正在尝试学习如何在subs之间来回传递值。我已经创建了几个宏底层,它们最终在它们之间反复使用相同的代码行。首先,我希望能够查找/计算列数和行数。这是我到目前为止所做的,但它没有用。

我还希望将它扩展到cols到行之外。

Public Sub main()
Dim lCols As Integer
Dim lRows As Integer

   lCols = countCols(Sheet1)

   Sheet1.Range("M2").Value = lCols

End Sub

Public Function countCols(sheetValue As Worksheet) As Variant
       countCols = sheetValue.Cells(Rows.Count, 1).End(x1Up).Row
   Exit Function
End Function

现在它在函数内挂起......似乎没有将“Sheet1”传递给sheetValue。

1 个答案:

答案 0 :(得分:2)

几点:

  1. 最好将行和列变量声明为long。见this
  2. 当您将变量lCols, lRows声明为Integer时,返回的函数类型也应为Integer
  3. 在您的情况下无需使用Exit FunctionExit Function用于退出函数并在函数调用后执行语句。但是在你的情况下,函数本身就会结束,因此不需要退出。
  4. 尝试以下

    Public Sub main()
        Dim lCols As Long, lRows As Long  'declared as long
        Dim ws As Worksheet
    
        Set ws = ThisWorkbook.Sheets("Sheet2")  'change Sheet2 to your data sheet
    
        lCols = countCols(ws)
        lRows = countRows(ws)
    
        ws.Range("M2").Value = lCols
        ws.Range("N2").Value = lRows
    
    End Sub
    
    Public Function countCols(sheetValue As Worksheet) As Long  'should return long
           countCols = sheetValue.Cells(1, sheetValue.Columns.Count).End(xlToLeft).Column
    End Function
    
    Public Function countRows(sheetValue As Worksheet) As Long  'should return long
           countRows = sheetValue.Cells(sheetValue.Rows.Count, 1).End(xlUp).Row
    End Function