vba excel 2010 环境(“用户名”)在另存为文件路径中不起作用

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/21098260/
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-08 17:33:10  来源:igfitidea点击:

vba excel 2010 Environ("username") not working in saveas filepath

vbaexcel-2010username

提问by cheapkid1

For some reason I can get the Message Box to tell me what the username is, but it doesn't work the same way within the save as path. I get a "Cannot find path" error.

出于某种原因,我可以让消息框告诉我用户名是什么,但它在另存为路径中的工作方式不同。我收到“找不到路径”错误。

Not sure how to fix this. I've also looked at references, and they seem like they are correct.

不知道如何解决这个问题。我也看过参考资料,他们似乎是正确的。

If I change the path to include the actual username per computer, the macro works fine. But I need this to be a global macro for any computer/user. Any help would be greatly appreciated.

如果我更改路径以包含每台计算机的实际用户名,则宏可以正常工作。但我需要它成为任何计算机/用户的全局宏。任何帮助将不胜感激。

Here is what I have:

这是我所拥有的:

Sub SAVEAS_2010()
'
' SAVEAS_2010 Macro
MsgBox Environ("username")

Dim UserName As String
UserName = Environ("username")

ChDir "C:\Users\" & UserName & "\Dropbox\Open Machine Schedule"
ActiveWorkbook.SaveAs FileName:= _
    "C:\Users\" & UserName & "\Dropbox\Open Machine Schedule\Open Machine Schedule - Current_2.xlsx" _
    , FileFormat:=xlOpenXMLWorkbook, CreateBackup:=False
End Sub

回答by Suresh

Seems an old question. But for anyone who stumble on this post, adding $worked for me - & Environ$("username") &

似乎是个老问题。但是对于任何偶然发现这篇文章的人来说,添加$对我有用- & Environ$("username") &

回答by Tim Edwards

Or you could just put VBA.in front of it. This fixes it for me. i.e. Environ("Username")becomes VBA.Environ("Username").

或者你可以放在VBA.它前面。这为我修复了它。即Environ("Username")变成VBA.Environ("Username").

回答by cheapkid1

Environ("UserProfile") &

This is what worked for me on 2007-2013 Excel versions.

这在 2007-2013 Excel 版本上对我有用。

回答by Andrew

Just found the same problem using VBA 7.1

刚刚使用 VBA 7.1 发现了同样的问题

Solution is to use

解决方法是使用

    path = Environ$("Userprofile") & "\Documents\temp_excel_files\"


    Environ$("Userprofile") 

Will give you something like "c:\users\Johnsmith" to put into your path.

会给你类似 "c:\users\Johnsmith" 的东西放在你的路径中。

Cheers! Andrew

干杯! 安德鲁