macros在Excel 2010隐藏行

我在VBA编程方面有点新鲜。 我在互联网上阅读了一些东西,但我找不到我需要或无法得到它的工作。 我的问题:

在单元格B6的工作表“工作表1”中给出了项目将被利用多less年的值。

在工作表'表格2'和'表格3'中,我做了50年的电子表格(第1年到第50年;第7行到第56行)。

在'表格1'的单元格b6中,我想input一个介于1到50之间的值。当值是49时,我想隐藏'表格2'和'表格3'中的第56行。 当值是48时,我想隐藏'sheet2'和'sheet 3'中的55:56行,依此类推。 这是我到目前为止,但我不能让它自动工作,当我更改单元格B6中的值:

Sub test1() If Range("sheet1!B6") = 50 Then Rows("52:55").EntireRow.Hidden = False Else If Range("sheet1!B6") = 49 Then Rows("55").EntireRow.Hidden = True Else If Range("sheet1!B6") = 48 Then Rows("54:55").EntireRow.Hidden = True End If: End If: End If: End Sub 

我希望有人能帮我解决我的问题。

谢谢

那么,你走在正确的道路上,本诺!

有一些关于VBA编程的提示可能会帮助你。

1-始终明确引用您要与之交互的工作表。 否则,Excel可能会“假设”你的代码适用于活动工作表,最终你会看到它把你的电子表格搞砸了。

2-正如lionz所提到的,请联系Excel提供的本地方法。 你可以在你的大部分技巧上使用它们。

3-显式声明你的variables…他们将显示每个对象在VBA中提供的方法列表。 这可能会节省您的时间在互联网上挖掘。

现在,我们有一个草案代码…

请记住,这个代码必须在Excel Sheet对象中,正如lionz所解释的那样。 它只适用于图纸2,由您自己select,以适应图纸2和图纸3。

希望能帮助到你!

 Private Sub Worksheet_Change(ByVal Target As Range) Dim oSheet As Excel.Worksheet 'We only want to do something if the changed cell is B6, right? If Target.Address = "$B$6" Then 'Checks if it's a number... If IsNumeric(Target.Value) Then 'Let's avoid values out of your bonds, correct? If Target.Value > 0 And Target.Value < 51 Then 'Let's assign the worksheet we'll show / hide rows to one variable and then ' use only the reference to the variable itself instead of the sheet name. ' It's safer. 'You can alternatively replace 'sheet 2' by 2 (without quotes) which will represent ' the sheet index within the workbook Set oSheet = ActiveWorkbook.Sheets("Sheet 2") 'We'll unhide before hide, to ensure we hide the correct ones oSheet.Range("A7:A56").EntireRow.Hidden = False oSheet.Range("A" & Target.Value + 7 & ":A56").EntireRow.Hidden = True End If End If End If End Sub 

你几乎得到它。 您正在隐藏活动工作表内的行。 这没关系。 但更好的方法是将其添加到哪里。

 Rows("52:55").EntireRow.Hidden = False 

 activesheet.Rows("52:55").EntireRow.Hidden = False 

我有奇怪的事情发生没有它。 至于它是自动的。 您需要在VBA编辑器的工作表macros中使用worksheet_change事件(不是模块,双击编辑器最左侧的sheet1)。在该工作表中,使用编辑器本身上方的下拉菜单(应该有2列表框)。 在左边的列表框将有你正在寻找的事件。 之后就是投入macros观。 它应该看起来像下面的代码,

 Private Sub Worksheet_Change(ByVal Target As Range) test1 end Sub 

而已。 任何时候你改变一些东西,它都会运行macrostesting1。