3
There are a number of things that might cause an error with the Save
operation but probably the most common is when we attempt to automate the filename creation, and don't account for illegal characters, which can't be part of a filename.
有许多事情可能会导致保存操作出错,但最常见的是当我们尝试自动创建文件名时,并且不考虑非法字符,这些字符不能是文件名的一部分。
In your case, since you are using date values, the presence of either a \
or /
in the date format would cause an error.
在您的情况下,由于您使用的是日期值,因此日期格式中存在\或/会导致错误。
This lists the reserved characters:
这列出了保留字符:
<
(less than)
<(小于)
>
(greater than)
>(大于)
:
(colon)
"
(double quote)
“(双引号)
/
(forward slash)
/(正斜杠)
\
(backslash)
|
(vertical bar or pipe)
| (竖杆或管道)
?
(question mark)
? (问号)
*
(asterisk)
For your case, you may simply use a double replace:
对于您的情况,您可以简单地使用双重替换:
CompanyNameSave = Replace(Replace(CompanyNameSave, "\", "-"), "/", "-")
However, that doesn't account for all illegal/reserved characters. It may be helpful to write a custom function that cleans filename strings:
但是,这并不能解释所有非法/保留字符。编写清除文件名字符串的自定义函数可能会有所帮助:
Function CleanFileName(name As String, Optional replaceBy As String = "_")
Const reservedChars As String = "<>:""""/\|?*"
Dim i As Integer
Dim ch As String
For i = 1 To Len(reservedChars)
ch = Mid(reservedChars, i, 1)
name = Replace(name, ch, replaceBy)
Next
CleanFileName = name
End Function
You could then call this function, immediately before trying to save the file, like:
然后,您可以在尝试保存文件之前立即调用此函数,例如:
CompanyNameSave = CleanFileName(CompanyNameSave, "-")
Note: If you omit the optional replaceBy
argument, it will default to using an underscore _
to replace the reserved characters.
注意:如果省略可选的replaceBy参数,则默认使用下划线_来替换保留字符。
Note also: This does not take in to account whether the file already exists.
另请注意:这不会考虑文件是否已存在。