gpt4 book ai didi

excel - 根据用户名筛选 excel

转载 作者:行者123 更新时间:2023-12-04 22:22:57 26 4
gpt4 key购买 nike

嗨,不确定这是否可以通过 excel 中的 vba 或任何方式实现。我想按用户名进行自动过滤。我有一个不同用户将使用的文件,它没有共享,因此一次只能一个人使用它。 excel是否可以识别用户名并将X列过滤为该用户名。显示与该用户相关的行。

ie Column X
John Doe
John Smith
Jane SMith

如果 john Smith 打开文件,它将自动过滤以仅显示 john smiths 行,如果用户名不在 X 列中,则显示全部?

这不是安全意识,所以如果有人取消过滤,这不是问题,只是很高兴拥有。

我知道excel可以调用用户名,因为我有一些发送文件并保存在文件名中的代码包括使用的用户名
Environ("Username"

任何帮助将不胜感激,因为我什至不知道从哪里开始

谢谢

最佳答案

假设您在 Sheet1 中有以下虚拟数据:

data

我们要过滤名称,第 3 列。

实现此目的的示例代码是:

Sub NameFilter()
Dim name As String
name = Environ("Username") 'e.g. "Mary"

ThisWorkbook.Sheets("Sheet1").Range("A1:C6").AutoFilter 3, "=" & name
End Sub

你可以把它放在 Workbook_Open打开工作簿时触发的函数:

Workbook Open

我们可以使它更加健壮和灵活,同时考虑到您在名称不存在时保持不过滤的要求。有关详细信息,请参阅下面的我的评论:
Sub NameFilter()
' Get the username for filtering
Dim name As String
name = Environ("Username")
' Define the filter range
Dim Rng As Range
Set Rng = ThisWorkbook.Sheets("Sheet1").Range("A1:C6")
' Define the column for filtering
Dim FiltColumn As Long
FiltColumn = 3
' Clear filters by default
Rng.AutoFilter FiltColumn
' Check if the name exists
NameExists = Application.Match(name, Rng.Columns(FiltColumn))
' Filter if the name does exist
If Not IsError(NameExists) Then
Rng.AutoFilter FiltColumn, "=" & name
End If
End Sub

关于excel - 根据用户名筛选 excel,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60776253/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com