VBA sub之间传递值

VBA Pass value between subs

我正在尝试学习如何在订阅者之间来回传递值。我创建了几个宏子,最终在它们之间一遍又一遍地使用相同的代码行。首先,我希望能够查看 up/count 列数和行数。这是我目前所拥有的,但它没有用。

我还想将其扩展到行之外。

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. 最好声明行和列变量一样长。参见 this
  2. 当您将变量 lCols, lRows 声明为 Integer 时,return 类型的函数也应该是 Integer
  3. 您的情况无需使用 Exit FunctionExit Function 用于退出函数并执行函数调用后的语句。但是,在您的情况下,函数本身在那里结束,因此不需要退出。

尝试关注

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