我正在尝试使用 VBA 代码将 Excel 工作簿保存为基于单元格数据的特定文件名并保存在特定的网络文件夹中。这是代码。
Private Sub CommandButton1_Click()
Dim Path As String
Dim FileName1 As String
Dim FileName2 As String
Path = "H:\testing folder\"
FileName1 = Range("A8")
FileName2 = Range("A11")
ActiveWorkbook.SaveAs Filename:=FileName1 & "_" & FileName2 & ".xlsx", FileFormat:=51
End Sub
该文件只是保存在H盘中,而不是H盘中的testing文件夹。另外,activeworkbook 行确实有 Filename:=Path & FileName1 等,但它保存在与“FileName1”前面的路径结束文件夹的名称相同的位置。
Private Sub CommandButton1_Click()
Dim Path As String
Dim FileName1 As String
Dim FileName2 As String
Path = "H:\testing folder\"
FileName1 = Range("A8")
FileName2 = Range("A11")
ActiveWorkbook.SaveAs Filename:=Path & FileName1 & "_" & FileName2 & ".xlsx", FileFormat:=51
End Sub
我想在使用路径时提出一些建议:
- 使用前先创建文件夹
- 检查范围是否填充了一些文本(特别是范围)
- 在单独的字符串中而不是在函数内部创建 FileName 参数(以便可以事先检查)
这里是一个示例,说明如何尝试此解释的技巧以及进一步的项目! 祝你好运,伙计!
> 您的代码
Private Sub CommandButton1_Click()
Dim strPath As String
Dim strFileName_ As String
'(1. Create your folder before using it)
'Create folders if necessary (Return path as String)
strPath = Create_Path("H:\testing folder\")
'Get range with File.Name
Set Rng_ = Union(Range("A8"), Range("A11")) 'Each range should be filled only with names (without extension nor Path)
Rng_.Select
'Get FileName for each Range
For Each text_ In Rng_
'(2. Check that Range is filled with some text (specially with ranges))
If Len(text_) = 0 Then Err.Raise 100, , "There is no text in range"
'(3. Create the FileName argument in a separate string instead of inside the function (so it can be inspected before hand))
strFileName_ = strPath & text_
'Save as xlOpenXMLWorkbook = 51
ActiveWorkbook.SaveAs FileName:=strFileName_, FileFormat:=xlOpenXMLWorkbook
'Check other FileFormat Constants at: https://learn.microsoft.com/en-us/office/vba/api/excel.xlfileformat
Next
End Sub
创建文件夹路径辅助功能
Function Create_Path(ByVal strPath As Variant) As String
strDriver = Split(strPath, ":")(0) & ":" 'If the drive is not specified, the new directory or folder is created on the current drive.
If Dir(strPath, vbDirectory) = "" Then 'Tests if strPath is already created
MkDir strPath 'Create a directory or folder
End If
'Fill function variable
Create_Path = strPath
End Function