简体   繁体   中英

Excel VBA Form control: Opening/creating an Excel file

I'd to create check if a file is exists using the shipNo and FilePath. If not, copy master.xls and rename the file according to shipNo. In all cases open the file afterwards.

Private Sub PDFButton_Click()
    On Error Resume Next
    Dim SourceFile As String, destFile As String, sourceExtension, shipNo As String

    'Initialize variables
    shipNo = Range("D4").Value
    FilePath = "C:\Users\*\Documents\QueueRecord\"
    SourceFile = "C:\Users\*\Documents\QueueRecord\Gen master.xls\"

    If (destFile) = "" Then
        Dim fso, createText As FileSystemObject

        Set fso = New Scripting.FileSystemObject
        fso.CopyFile SourceFile, FilePath & "SampleFileCopy.xls\"
        Set createText = fso.CreateTextFile(FilePath, True, True)
        createText.Write "success"
        createText.Close

        If fso.FileExists(FilePath & "SampleFileCopy.xls\") Then
            MsgBox "Success"
        End If
    End If
    ActiveWorkbook.FollowHyperlink ("C:\Users\*\Documents\QueueRecord\" + shipNo + ".xls\")
End Sub

In my tests SampleFileCopy.xls is never created, nor is the textFile created.

destFile will always be empty the way you have it written. I'm assuming you want the line to look like:

If dir(FilePath & shipNo & ".xls") = "" Then

Also, remove all the back slashes after the full file paths.

this:

"C:\Users\*\Documents\QueueRecord\Gen master.xls\"

should be this:

Environ("userprofile") & "\Documents\QueueRecord\Gen master.xls"

Also, as stated in the comments, remove the "on error resume next" so you know where the code is breaking.

Full code below, based on the assumption that destFile is supposed to be filepath and shipNo:

Private Sub PDFButton_Click()
    Dim SourceFile As String, destFile As String, sourceExtension, shipNo As String

    'Initialize variables
    shipNo = Range("D4").Value
    FilePath = Environ("userprofile") & "\Documents\QueueRecord\"
    SourceFile = Environ("userprofile") & "\Documents\QueueRecord\Gen master.xls"

    If Dir(FilePath & shipNo & ".xls", vbDirectory) = "" Then
        Dim fso As FileSystemObject

        Set fso = New Scripting.FileSystemObject
        fso.CopyFile SourceFile, FilePath & "SampleFileCopy.xls"

        'create text file
        TextFile = FreeFile
        Open FilePath & shipNo & ".txt" For Output As TextFile
        Print #TextFile, "success";
        Close TextFile

        If fso.FileExists(FilePath & "SampleFileCopy.xls") Then
            MsgBox "Success"
        End If
    End If
    ActiveWorkbook.FollowHyperlink (Environ("userprofile") & "\Documents\QueueRecord\" & shipNo & ".xls")
End Sub

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM