在 vba 中设置 FilePath 和 FileName
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/34725515/
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
Setting FilePath and FileName in vba
提问by Doug Coats
Ok so I think I have gotten confused on how to do this and maybe I am doing something obviously wrong?
好的,所以我想我对如何做到这一点感到困惑,也许我在做一些明显错误的事情?
Here is my code :
这是我的代码:
Private Sub CommandButton1_Click()
Dim wbI As Workbook, wbO As Workbook, wb1 As Workbook
Dim wsI As Worksheet, wsO As Worksheet, ws1 As Worksheet
filelocation1 = "C:\Users\Public\Desktop_" & Format(Date, "ddmmyyyy") & "Production.xls"
Set wbI = ThisWorkbook
Set wsI = wbI.Sheets("Production")
Set wbO = Workbooks.Add
With wbO
Set wsO = wbO.Sheets("Sheet1")
ActiveWorkbook.SaveAs Filename:=filelocation1 '******
wsI.Range("A1:C100").Copy
wsO.Range("A1").PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, _
SkipBlanks:=False, Transpose:=False
End With
However at the asterisked line I get a run time error (included as image). I think it's because I am saving the file incorrectly...but I thought this was correct? Is it because I am using a file path instead of a file name? Would I need ot add at the end of the path "Name".xls? Or do I need to separate file name and file path?
然而,在星号行我得到一个运行时错误(包含在图像中)。我认为这是因为我保存文件不正确...但我认为这是正确的?是因为我使用的是文件路径而不是文件名吗?我需要在路径“Name”.xls 的末尾添加吗?或者我需要将文件名和文件路径分开吗?
Thanks in advance :)
提前致谢 :)
EDIT: Now Things are working however, the file is being dumped in "C:\Users\Public" location with DESKTOP added to the name (instead of "C:\Users\Public\Desktop" . I have tried all sorts of stuff trying to route it to the correct location, like adding a "_" at the end as well as other tricks that have not worked.
编辑:现在一切正常,文件被转储到 "C:\Users\Public" 位置,并在名称中添加了 DESKTOP(而不是 "C:\Users\Public\Desktop" 。我尝试了各种各样的东西尝试将其路由到正确的位置,例如在末尾添加“_”以及其他不起作用的技巧。
How do i fix this?
我该如何解决?
SOLVED :
解决了 :
filelocation1 = "C:\Users\Public\Desktop" & "\" & Format(Date, "ddmmyyyy") _
& "Production.xls"
回答by Jordan
You need to include the file name in the file path e.g. "C:\Users\Public\Desktop\Name.xls"
您需要在文件路径中包含文件名,例如 "C:\Users\Public\Desktop\Name.xls"
回答by Arazio
Syntax error i believe
我相信语法错误
I tend to use something like
我倾向于使用类似的东西
dim filelocation as string
dim fileext as string
dim filestring as string
Then use "C:\Users\Public\Desktop\" as your file location and set the fileext as whatever you like e.g. if you wanted to say type you own file name into a text box then fileext = textbox.textthen it's a case of filestring = filelocation & fileext. This sort of method allows you flexibility if you play around with it
然后使用“C:\Users\Public\Desktop\”作为您的文件位置,并将fileext 设置为您喜欢的任何内容,例如,如果您想说在文本框中键入您自己的文件名,fileext = textbox.text那么它是filestring = filelocation & fileext. 这种方法可以让你灵活地玩弄它


