VBA Excel 宏:使用范围对不同的工作表进行操作

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2656443/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-11 11:33:45  来源:igfitidea点击:

VBA Excel macro: use Range to act on a different worksheet

excelvbaexcel-vba

提问by David Oneill

I am very much a beginner when it comes to VBA programming.

在 VBA 编程方面,我是一个初学者。

I have a Macro that hides or shows columns based on the value in one cell:

我有一个根据一个单元格中的值隐藏或显示列的宏:

Sub HideColumnsMacro()
 Range("b8:o8").EntireColumn.Hidden = False
 v1 = Range("b2").Value + 1
 If v1 < 12 Then
  With Range("b8")
   Range(.Offset(0,v1), .Offset(0, 12)).EntireColumn.Hidden = True
  End With
 End If
End Sub

I want to be able to get this same functionality when I change a cell on a different sheet. Is there a way I can tell this Macro to act on this sheet, when it is run from a different one?

当我更改不同工作表上的单元格时,我希望能够获得相同的功能。当它从不同的工作表运行时,有没有一种方法可以告诉这个宏在这张工作表上起作用?

回答by Thomas

In your macro, specify the exact sheet:

在您的宏中,指定确切的工作表:

Sheets("Sheet1").Range("b8:o8").EntireColumn.Hidden = False

回答by GSerg

Qualify your Ranges with the name of the worksheet:

Range使用工作表的名称限定您的s:

Sheet1.Range("b8:o8").EntireColumn.Hidden = False