尝试使用Excel和特定网络路径另存为Excel工作簿

w41d8nur  于 2023-11-20  发布在  其他
关注(0)|答案(2)|浏览(139)

我尝试使用Excel代码来保存一个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驱动器中的测试文件夹。此外,activeworkbook行确实有Film:=Path & FileName1等,但它保存在与路径结束文件夹的名称相同的地方,在“FileName1”前面。

4xy9mtcn

4xy9mtcn1#

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

字符串

ih99xse1

ih99xse12#

我想在处理路径时提出一些建议:
1.在使用文件夹之前创建它
1.检查Range是否填充了一些文本(特别是范围)
1.在一个单独的字符串中而不是在函数中创建文件名参数(这样可以事先检查它)
这里是一个例子,你如何尝试这个解释的提示和进一步的项目!祝你好运伙计!

>您的代码

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

相关问题