MS Access VBA FileSystemObject 不接受其中包含空格的路径
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7826309/
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
MS Access VBA FileSystemObject does not accept path with spaces in them
提问by Bill Software Engineer
How do I get around the limitation VBA have of not allowing spaces in file path when using the FileSystemObject?
在使用 FileSystemObject 时,如何解决 VBA 不允许文件路径中有空格的限制?
Here is my code:
这是我的代码:
from= "C:\Users\MyAccount\Desktop\a.txt"
to= "C:\Users\MyAccount\Desktop\Folder Name With Spaces\b.txt"
Dim fso As New FileSystemObject
Set fso = CreateObject("Scripting.FileSystemObject")
fso.CopyFile from, to
I have already tried the trick with adding " before any spaces, it doesn't work. The "Bad FileName or Number" error actually pops up.
我已经尝试过在任何空格前添加 " 的技巧,但它不起作用。实际上会弹出“错误的文件名或编号”错误。
I have also tried to replace any spaces with %20, which also does not work.
我也尝试用 %20 替换任何空格,这也不起作用。
To clarify, I don't know the path beforehand, it is entered by the user.
澄清一下,我事先不知道路径,它是由用户输入的。
回答by Jean-Fran?ois Corbett
There's no restriction around having spaces in filenames or paths, either in VBA or when using the FSO. You must have some other problem.
无论是在 VBA 中还是在使用 FSO 时,文件名或路径中的空格都没有限制。你肯定有其他问题。
For example I don't think FSO will create a destination folder if it doesn't already exist.
例如,如果目标文件夹不存在,我认为 FSO 不会创建它。
Also: you don't need to use Createobject if you Dim ... As New ...: your object is created in the Dim statement.
另外:如果 Dim ... As New ...,则不需要使用 Createobject:您的对象是在 Dim 语句中创建的。
回答by NG. Hai Tuan
My solution to the same issue:
我对同一问题的解决方案:
Dim folderPath As String
folderPath = "D:\MyData\BackUp\capdat\City Name"
If Len(Dir$((folderPath & "\OLDData" & Format(Date, "-ddmmyyyy") & ".accdb"))) > 0 Then
Kill (folderPath & "\OLDData" & Format(Date, "-ddmmyyyy") & ".accdb"
Else
Do something
End if
回答by Sam Holder
its a while since I did any VBA but I think you need to enclose your strings in quotes to negate the spaces in the paths, so does this work:
自从我做任何 VBA 以来已经有一段时间了,但我认为您需要将字符串括在引号中以否定路径中的空格,这是否有效:
fso.CopyFile """" + from + """", """" + to+ """"
EDIT:
编辑:
This sitesuggested this routine:
该站点建议使用此例程:
Private Function GetQuotedArgument(ByVal argument As String) As String Const Quote As String = """" Return String.Format("{0}{1}{0}", Quote, argument) End Function
Private Function GetQuotedArgument(ByVal argument As String) As String Const Quote As String = """" Return String.Format("{0}{1}{0}", Quote, argument) End Function
giving:
给予:
fso.CopyFile GetQuotedArgument(from), GetQuotedArgument(to)
Failing that you'll have to resort to short forms of the file names... Microsoft article on doing that here, not sure if it applies to VBA though