作为一个学习练习,我创建了我的第一个Excel VBA函数来返回任何Excel表中的活动单元格行号(而不是工作表本身)。本质上,它只是找到工作表中的活动行,然后找到表头的行号,然后从单元格行号中减去行号,返回表格的行号,然后可以在后续代码中使用。然而,虽然它有效,但它看起来并不是最有效的,有人能改进它吗?
Sub TableRow()
Dim LORow As Integer
Dim TbleCell As Range
Set TbleCell = Activecell
Call FuncTableRow(TbleCell, LORow)
MsgBox LORow
End Sub
Public Function FuncTableRow(ByRef TbleCell As Range, LORow As Integer) As Range
Dim LOName As String
Dim LOHeaderRow, Row As Integer
LOName = Activecell.ListObject.Name
Row = Activecell.Row
LOHeaderRow = ActiveSheet.ListObjects(LOName).HeaderRowRange.Row
LORow = Row - LOHeaderRow
Debug.Print (LORow)
End Function发布于 2021-11-02 12:38:57
这个问题可能会因为不够具体而结束,但(对我来说)最明显的问题是您对自定义函数的使用。您的函数实际上并没有返回任何东西,它只是运行一个debug print。要让函数实际返回行号,可以将其设置为Long (not integer)类型,并将函数名=包含到行号中。
我实际上并没有测试你的函数,但是假设LORow打印正确的答案是错误的,那么它应该是这样工作的:
Public Function FuncTableRow(ByRef TbleCell As Range, LORow As Integer) As Long
Dim LOName As String
Dim LOHeaderRow, Row As Integer
LOName = Activecell.ListObject.Name
Row = Activecell.Row
LOHeaderRow = ActiveSheet.ListObjects(LOName).HeaderRowRange.Row
LORow = Row - LOHeaderRow
Debug.Print (LORow)
FuncTableRow = LORow
End Function你也不需要插入一个函数,你可以在subroutine.
LORow作为输入变量,然后改变它。这通常是一个坏的practice.
TbleCell.Worksheet
Dim LOHeaderRow, Row As Integer的一部分的ActiveSheet实际上应该是Dim LOHeaderRow as Long, Row As Long。正如您当前所拥有的,LOHeaderRow是undefined/Variant.可能还有更多。我会用一个更简单的任务重新启动您的进程,即返回工作表中最后使用的单元格。有十几种方法可以做到这一点,还有很多帮助示例。
发布于 2021-11-02 12:57:10
看看这个TheSpreadsheetGuru。
这里有一些可能对你有帮助的变量。
Sub TableVariables()
Dim ol As ListObject: Set ol = ActiveSheet.ListObjects(1)
Dim olRng As Range: Set olRng = ol.Range ' table absolute address
Dim olRngStr As String: olRngStr = ol.Range.Address(False, False) ' table address without absolute reference '$'
Dim olRow As Integer: olRow = ol.Range.Row ' first row position
Dim olCol As Integer: olCol = ol.Range.Column ' first column position
Dim olRows As Long: olRows = ol.Range.Rows.Count ' table rows including header
Dim olCols As Long: olCols = ol.ListColumns.Count ' table columns
Dim olListRows As Long: olListRows = ol.ListRows.Count ' table rows without header
End Subhttps://stackoverflow.com/questions/69810515
复制相似问题