首页 > 解决方案 > 在选定的工作表而不是活动工作表上运行代码

问题描述

我将我的 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

标签: excelvba

解决方案


当你使用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.


推荐阅读