excel - 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
解决方案
您的代码的意图并不完全清楚,但它似乎试图找到工作表的使用范围(带有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
除此之外,您的代码还有几个问题:
您通过
ws
但从不使用它,而是恢复到ActiveSheet
函数体中。您
Integer
用来代表行号和列号——但这有溢出的风险。只需使用Long
.当您声明一些变量时,您不会声明其他变量。这是不一致的,并且可能是错误的来源。使用
Option Explicit
是强迫自己更加一致的好方法。事实上,您可以通过使用 VBA 编辑器选项(在工具/选项下)中的“需要变量声明”选项一劳永逸地完成它。
推荐阅读
- typescript - 强制执行接口值的类型
- powerbi - 显示数据库中的图像
- sql - 如何忽略 Hive Lead 函数中的空值
- ms-access - 如何在 Microsoft Access 中执行嵌套的 If / and 语句?
- javascript - 如何使用 reactjs 挂钩将结果从一个组件传递到另一个组件?
- javascript - TypeError:组件不是添加 forwardRef 的函数
- c# - 在 EF Core 5 中将实例从一个集合移动到另一个集合
- python - Groupby 并加入 Pandas 数据框以获取带有换行符的字符串列
- c# - 根据解决方案中的数据库项目验证 .NET 项目中的存储过程
- git - GIT & GIT GUI 不使用 SSH 密钥