gpt4 book ai didi

excel - 2 种功能合二为一

转载 作者:行者123 更新时间:2023-12-04 19:55:12 26 4
gpt4 key购买 nike

我编写了这两个函数,它们返回工作表中最后一行和最后一列的值。它们相同但返回不同的值。是否可以以简单的方式将它们组合成 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

最佳答案

您的代码的意图并不完全清楚,但它似乎试图找到工作表的使用范围(其中 i_asuction = 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 编辑器选项(在“工具/选项”下)中的“需要变量声明”选项来一劳永逸地完成此操作。

关于excel - 2 种功能合二为一,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65991545/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com