首页 > 解决方案 > 2个功能合二为一

问题描述

我编写了这 2 个函数,它们返回工作表中最后一行和最后一列的值。它们相同但返回不同的值。是否可以以简单的方式将它们组合为 1 个功能?我考虑全局变量 i_lRow 和 i_lColumn 并将值赋给函数或做一些类,例如 wsSetting 并添加名为 lastRow、lastColumn 的属性。

Sub testWywolania()
variable = GetMaxLastColumn(ActiveSheet)
variable2 = GetMaxLastRow(ActiveSheet)
MsgBox variable & vbCrLf & variable2
End Sub

Function GetMaxLastRow(ws As Worksheet) As Integer
Dim i_lr As Integer, i_lc As Integer, i_tempLc As Integer, i_assumption As Integer, i_assumptionR As Integer, i_assumptionC As Integer, i_aVal As Integer
Dim r_workRange As Range

i_lc = 0
i_lr = 0
i_assumption = 30
i_aVal = i_assumption
i_assumptionC = i_assumption
i_assumptionR = i_assumption

Do
    i = i + 1
    Do
        j = j + 1
        i_tempLc = ActiveSheet.Cells(i, Columns.Count).End(xlToLeft).Column
        i_tempLr = ActiveSheet.Cells(Rows.Count, j).End(xlUp).Row
        If i_tempLc > i_lc Then i_lc = i_tempLc:   i_tempLc = 0
        If i_tempLr > i_lr Then i_lr = i_tempLr: i_tempLr = 0
        If i >= i_aVal And j >= i_aVal Then
            i_assumptionR = i_lr
            i_assumptionC = i_lc
        End If
    Loop While j <= i_assumptionC
Loop While i <= i_assumptionR

GetMaxLastRow = i_lr
End Function

Function GetMaxLastColumn(ws As Worksheet) As Integer
Dim i_lr As Integer, i_lc As Integer, i_tempLc As Integer, i_assumption As Integer, i_assumptionR As Integer, i_assumptionC As Integer, i_aVal As Integer
Dim r_workRange As Range

i_lc = 0
i_lr = 0
i_assumption = 30
i_aVal = i_assumption
i_assumptionC = i_assumption
i_assumptionR = i_assumption

Do
    i = i + 1
    Do
        j = j + 1
        i_tempLc = ActiveSheet.Cells(i, Columns.Count).End(xlToLeft).Column
        i_tempLr = ActiveSheet.Cells(Rows.Count, j).End(xlUp).Row
        If i_tempLc > i_lc Then i_lc = i_tempLc:   i_tempLc = 0
        If i_tempLr > i_lr Then i_lr = i_tempLr: i_tempLr = 0
        If i >= i_aVal And j >= i_aVal Then
            i_assumptionR = i_lr
            i_assumptionC = i_lc
        End If
    Loop While j <= i_assumptionC
Loop While i <= i_assumptionR

GetMaxLastColumn = i_lc
End Function

标签: excelvba

解决方案


您的代码的意图并不完全清楚,但它似乎试图找到工作表的使用范围(带有i_assumption = 30一个无法解释的数字,旨在限制手动搜索该范围的范围,以便运行时可以接受)。如果是这样,您可以完全删除您的两个函数并直接使用UsedRange工作表对象的属性。以下给出与您的测试子相同的输出:

Sub test()
    Dim variable As Long, variable2 As Long
    Dim R As Range
    Set R = ActiveSheet.UsedRange
    variable = R.Cells(1, 1).Column + R.Columns.Count - 1
    variable2 = R.Cells(1, 2).Row + R.Rows.Count - 1
    MsgBox variable & vbCrLf & variable2
End Sub

除此之外,您的代码还有几个问题:

  1. 您通过ws但从不使用它,而是恢复到ActiveSheet函数体中。

  2. Integer用来代表行号和列号——但这有溢出的风险。只需使用Long.

  3. 当您声明一些变量时,您不会声明其他变量。这是不一致的,并且可能是错误的来源。使用Option Explicit是强迫自己更加一致的好方法。事实上,您可以通过使用 VBA 编辑器选项(在工具/选项下)中的“需要变量声明”选项一劳永逸地完成它。


推荐阅读