excel - 宏仅在活动工作表中启动
问题描述
我是 excel VBA 的新手。我在互联网上找到了一个很好地解决了我的问题的宏。但是还有一个小问题,这个宏只在活动表上运行。我想在我指定的工作表(例如 sheet1)上运行它。我把这个宏放在这里,请指导我解决这个问题。
Sub SelectByValue(Rng1 As Range, TargetValue As String)
Dim MyRange As Range
Dim Cell As Object
'Check every cell in the range for matching criteria.
For Each Cell In Rng1
If Cell.Value > TargetValue Then
If MyRange Is Nothing Then
Set MyRange = Range(Cell.Address)
Else
Set MyRange = Union(MyRange, Range(Cell.Address))
End If
End If
Next
'Select the new range of only matching criteria
MyRange.Select
End Sub
Sub CallSelectByValue()
'Call the macro and pass all the required variables to it.
Call SelectByValue(Range("A1:D500"), "")
End Sub
解决方案
您可以尝试将工作表选择构建到Sub CallSelectByValue()
可能?
我自己还不是专业人士,但这里有一个 coupla 建议:
1.在CallSelectByValue
Sub中定义工作表
(复制你的代码并编辑它:)
Sub CallSelectByValue()
Dim Sheet as WorkSheet
Set Sheet = Sheets("Sheet1") 'insert relevant sheet name
'Call the macro as before, but include the sheet reference in the range
Call SelectByValue(Sheet.Range("A1:D500"), "")
'Update after comments;
Sheet.Activate
End Sub
2.每次输入所需的表(在不同的表上重复使用子时)
Sub CallSelectByValue()
'Find out what sheet to refer to
Dim SheetName As String
Dim Sheet As Worksheet
FindSheetName:
SheetName = InputBox("Please enter the name of the sheet you'd like it to refer to", "Sheet Selection")
'Check the typed value is actually a sheet name
If IsEmpty(Sheets(SheetName)) Then
MsgBox "That sheet couldn't be found. Try again", vbOkOnly+vbCritical, "Sheet not found"
GoTo FindSheetName 'loops you back to re-try typing it in
Else
'If it matches up, assign that value to the Sheet variable
Sheet = Sheets(SheetName)
End If
'Update after comments;
Sheet.Activate
'Call the macro and pass all the required variables to it, including the sheet reference
Call SelectByValue(Sheet.Range("A1:D500"), "")
End Sub
试试这些,让我知道它们是否有效。
推荐阅读
- ansible - 将脚本变量的值传递给剧本输出
- javascript - Symfony Forms - 根据选择动态添加/删除字段
- java - Spring boot,事务性与调度一起使用
- hyperledger-fabric - Hyperledger Fabric 链码可以调用外部本地应用程序/二进制文件吗?
- laravel - 如何从外部 url 检索文件?
- pandas - 根据列值选择特定的行
- ptc-windchill - 如何通过 Windchill 中的 QuerySpec 获取本地属性值
- python-3.x - 为什么我的文本文件被视为单个字符串?
- angularjs - Chrome 更新(angularjs 和 bootstrap-ui)后,当光标在模态之外释放时,模态关闭
- python - 有没有办法创建一个函数来加载目录中的所有数据文件,然后输出它们的文件名和内容?-Python 3