excel - 在选定的工作表而不是活动工作表上运行代码
问题描述
我将我的 ws 变量设置为第一个工作表,但我的代码在活动工作表上运行。
此代码从 Sheet2 上的一个按钮运行,我正在使用Sheets(1).Select
,因为第一个工作表的名称可能会有所不同。
我需要更改什么才能让我的代码在 Sheets(1) 上运行?
Function Test()
Dim ws As Worksheet
Dim lColumn As Long
Dim lRow As Long
Dim myRange As Range
Dim cell As Range
Set ws = Sheets(1)
With ws
lColumn = ws.UsedRange.Columns.Count
lRow = Cells(Rows.Count, 2).End(xlUp).Row
colName = Split(Worksheets(1).Cells(1, lColumn).Address, "$")(1)
Range("A1: " & colName & "1").Font.Bold = True
Set myRange = Range("A1: " & colName & "1")
For Each cell In myRange
cell.Interior.Pattern = xlSolid
cell.Interior.PatternColorIndex = xlAutomatic
cell.Interior.ThemeColor = xlThemeColorDark1
cell.Interior.TintAndShade = -0.249977111117893
cell.Interior.PatternTintAndShade = 0
Next
End with
End Function
解决方案
当你使用With
语句时,你仍然需要.
在属性前面加上前缀,以便对With
块变量进行成员调用。
我lColumn = ws.UsedRange.Columns.Count
改为lColumn = .UsedRange.Columns.Count
.Range("A1: " & colName & "1").Font.Bold = True
Set myRange = .Range("A1: " & colName & "1")
通过不使用.
VBA 认为您正在引用ActiveSheet
.
推荐阅读
- python - RuntimeError:模型类rideshare.models.rideshare 没有声明明确的app_label,并且不在INSTALLED_APPS 中的应用程序中
- apache-kafka - Kafka 中的不公平领导者选举 - 所有分区的领导者都相同
- c++ - 了解为什么它不能使用 memcpy 正确复制
- javascript - node.js如何等待异步操作完成
- tensorflow - Keras model.reset_states() 不适用于 tf.train.MonitoredTrainingSession
- sql - 如何获取找到 MAX() 值的行号或 ID
- layout - 我们可以在 vscode 中结合网格布局和终端面板吗?
- c++ - std::function 和函数模板
- c# - System.AccessViolationException 发生在 TextView.Buffer
- arrays - 具有特殊性质的秩和非秩排列