运行时错误'1004':对象_Workbook的方法SaveAs失败

时间:2018-07-27 22:22:53

标签: excel vba compiler-errors save

我正在编写一个程序,该程序根据工作簿中的某些单元格值将工作簿保存到特定的文件夹中。一切都会正常进行,直到到达ActiveWorkbook.SaveAs行,并在其中出现运行时错误1004。

`Sub Tester()

Dim qNum, fldr As String
Dim custName As String
Dim myFileName As String
Dim completePath As String
Dim division As String

custName = Range("B12").Value
qNum = Range("B19").Value

If custName = "CNUL - Albian" Then
    custName = "CNRL"
    division = "Albian"
End If
If custName = "CNUL - Horizon" Then
    custName = "CNRL"
    division = "Horizon"
End If
If custName = "CNRL - Albian" Then
    custName = "CNRL"
    division = "Albian"
End If
If custName = "CNRL - Horizon" Then
    custName = "CNRL"
    division = "Horizon"
End If

If custName = "CNRL" Then
    fldr = GetMatchingPathCNRL(qNum, custName, division) '<< find the        matching folder
    If Len(fldr) > 0 Then
        Debug.Print "Found folder for customer=" & custName & _
                        ", Qnum=" & qNum & vbLf & fldr
            '...use this path

    Else
        MsgBox "No matching folder!", vbExclamation
    End If
Else
    fldr = GetMatchingPath(qNum, custName) '<< find the matching folder
    If Len(fldr) > 0 Then
        Debug.Print "Found folder for customer=" & custName & _
                    ", Qnum=" & qNum & vbLf & fldr
        '...use this path

    Else
        MsgBox "No matching folder!", vbExclamation
    End If
End If


myFileName = custName & " " & qNum & " " & "MTO Rev A"
completePath = fldr & "\" & myFileName

ActiveWorkbook.SaveAs Filename:=completePath
End Sub

Function GetMatchingPath(qNum, custName) As String
Const ROOT As String = "P:\MyCompany\" '<< adjust to suit
Dim f
f = Dir(ROOT & custName & "\*" & qNum & "*", vbDirectory)
GetMatchingPath = ROOT & custName & "\" & f
End Function


Function GetMatchingPathCNRL(qNum, custName, division) As String
Const ROOT As String = "P:\MyCompany\" '<< adjust to suit
Dim f
f = Dir(ROOT & custName & "\" & division & "\*" & qNum & "*", vbDirectory)
GetMatchingPathCNRL = ROOT & custName & "\" & f
End Function

` 这样的想法是,如果客户是CNRL,则需要多一层文件夹。开头的4个“ if”语句只是为了引导人们可以在电子表格中输入信息的几种不同方式。

当我进入保存文件行时,总是会遇到1004错误,但是变量都存储了正确的名称和文件夹路径。有什么想法吗?

1 个答案:

答案 0 :(得分:2)

division返回的路径中没有GetMatchingPathCNRL

f = Dir(ROOT & custName & "\" & division & "\*" & qNum & "*", vbDirectory)
GetMatchingPathCNRL = ROOT & custName & "\" & f

应该是

GetMatchingPathCNRL = ROOT & custName & "\" & division & "\" & f

编辑:我认为最好将“路径”逻辑集中到一个位置,而不是具有两个不同的功能,而您必须弄清楚要调用哪个功能...

Function GetMatchingPath(qNum, custName, division) As String
    Const ROOT As String = "P:\MyCompany\" '<< adjust to suit
    Dim fPath As String, f

    fPath = ROOT & custName & "\"
    If custName = "CNRL" Then fPath = fPath & division & "\"

    f = Dir(fPath & "*" & qNum & "*", vbDirectory)
    GetMatchingPath = IIf(f <> "", fPath & f, "")
End Function