简体   繁体   English

通过VBA隐藏Excel工作表

[英]Hide excel worksheet via VBA

I have a workbook that has a number of worksheets each one with a colaborator name on it (Windows login username). 我有一本工作簿,其中包含许多工作表,每个工作表上都有一个协作者名称(Windows登录用户名)。

I've tried via VBA to loop through all Worksheets to match the actual Windows Logged On username with the matching Worksheet, and after the match is done, only that Worksheet is kept visible (with all the others being hiden). 我已经尝试通过VBA遍历所有工作表,以使实际的Windows登录用户名与匹配的工作表相匹配,并且在匹配完成后,只有该工作表保持可见(所有其他工作表都被隐藏)。

I've managed to do this partially but i can only do it untill it finds the matching worksheet. 我已经设法做到了这一点,但我只能做到这一点,直到找到匹配的工作表。 For example, if the matching username is the third worksheet (in a total of ten for example) the code stops there. 例如,如果匹配的用户名是第三个工作表(例如,总共十个工作表),则代码在那里停止。 I want it to run through all worksheets and only then hide the non matching Worksheets. 我希望它遍历所有工作表,然后才隐藏不匹配的工作表。

First i have the following module: 首先,我有以下模块:

Sub WorksheetFilter()

Dim Username As String
Dim Worksheetname As String

Worksheetname = ActiveWorkbook.ActiveSheet.Name

Username = Environ("Username")

If Worksheetname <> Username Then
   ActiveSheet.Visible = False
End If

End Sub

Then, i call the previous module on the Workbook_Open() event: 然后,我在Workbook_Open()事件上调用上一个模块:

Option Explicit
Dim WS As Worksheet

Private Sub Workbook_Open()

For Each WS In ActiveWorkbook.Worksheets
    WorksheetFilter
Next
End Sub

Any hints on how this can be achieved? 关于如何实现的任何提示?

Thanks, Vítor 谢谢,Vítor

Use the code below, and put it in the Workbook module under the Workbook_Open event. 使用下面的代码,并把它在Workbook模块下Workbook_Open事件。

Just loop through all sheets and compare each one with the username . 只需循环浏览所有工作表,然后将每个工作表与username进行比较即可。

Option Explicit

Public Sht As Worksheet


Private Sub Workbook_Open()

For Each Sht In ThisWorkbook.Sheets

    If Sht.Name = Environ("Username") Then
        Sht.Visible = xlSheetVisible
    Else
        Sht.Visible = xlSheetHidden

        ' option 2: use very hidden, only able to unhide through code (unable to unhide using right-click)
        'Sht.Visible = xlSheetVeryHidden
    End If

Next Sht

End Sub

Please see below: chopped your code around a bit. 请参见以下内容:将您的代码砍了一些。 You do not need to defien the worksheets name. 您无需定义工作表名称。 This is for the module level, you can call it in the workbook open event as per usual 这是针对模块级别的,您可以照常在工作簿打开事件中调用它

Option Explicit
Dim ws As Worksheet
Dim Username As String
Sub WorksheetFilter()

Username = Environ("Username")

For Each ws In ActiveWorkbook.Worksheets


    If ws.Name <> Username Then
        ws.Visible = False

    Else
        ws.Visible = True
    End If
Next ws
End Sub

Please let me know how this works for you! 请让我知道它如何为您服务! :) :)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM