复制 Excel 文件并立即在新文件中启动用户表单

问题描述 投票:0回答:1

我有代码向用户展示一个带有 2 个文本框的简单用户表单。然后,它将 Excel 文件复制到服务器上的特定位置,并根据用户输入适当命名。那部分一切都很好。但现在我希望从新复制的文件中弹出一个用户表单,供用户开始填写,但我陷入了困境。我尝试了很多不同的调用用户表单的方法,但所有方法都会导致错误。我已经确定宏已启用、受信任等,但我只是没有取得任何进展。这是第一个用户表单“确定”按钮的现有代码:

Private Sub CommandButton1_Click()
    Dim jobNumber As String
    Dim customerCode As String
    Dim SourceFilePath As String
    Dim newFullPath As String
    Dim JobsFolder As String
    Dim folderPath As String
    Dim fso As Object

    ' Get the user inputs
    jobNumber = TextBox1.Text
    customerCode = TextBox2.Text

    ' Ensure the inputs are not empty
    If jobNumber = "" Or customerCode = "" Then
        MsgBox "Please enter both the job number and customer code.", vbExclamation
        Me.Hide
        Me.Show
        Exit Sub
    End If
    
    ' Extract the part before the first hyphen
    JobsFolder = Split(jobNumber, "-")(0)

    ' Construct the new full path
    newFileName = "MASTER BOM " & jobNumber & " ASM 0.xlsm"
    folderPath = "\\pmw-fs1\Storage-PMW\Jobs\" & JobsFolder & " " & UCase(customerCode)
    newFullPath = folderPath & "\" & newFileName

    ' Check if the folder exists
    Set fso = CreateObject("Scripting.FileSystemObject")
    If Not fso.FolderExists(folderPath) Then
        Dim response As VbMsgBoxResult
        response = MsgBox("The folder for """ & JobsFolder & " " & UCase(customerCode) & """ does not exist. Are you certain you want to create this folder?", vbYesNo + vbExclamation, "Folder Not Found")
        If response = vbYes Then
            ' Create the folder
            fso.CreateFolder folderPath
        Else
            ' Display the userform again with current inputs
            Me.Hide
            ' Re-fill the textboxes with the current inputs
            TextBox1.Text = jobNumber
            TextBox2.Text = UCase(customerCode)
            Me.Show
            Exit Sub
        End If
    End If

    ' Get the current file path
    SourceFilePath = "\\pmw-fs1\Storage-PMW\Jobs\_Automation\MasterBomVBA\Master Bom Data.xlsm"

    ' Save a copy of the source workbook to the new location with the new name
    Workbooks.Open SourceFilePath
    ActiveWorkbook.SaveCopyAs newFullPath
    ActiveWorkbook.Close SaveChanges:=False

    ' Open the new file and set it as the active workbook
    Dim newWorkbook As Workbook
    Set newWorkbook = Workbooks.Open(newFullPath)
    newWorkbook.Activate
    
    InitialInput.Hide 'the 2-textbox userform
    TextBox1.Text = ""
    TextBox2.Text = ""
    
    ' Show the PartEntry userform from the new workbook
    newWorkbook.Application.Run "PartEntry.Show"
 
End Sub
excel vba userform file-copying
1个回答
0
投票

在源工作簿上添加宏

Sub PartEntryShow()
    PartEntry.Show
End Sub

然后将

newWorkbook.Application.Run "PartEntry.Show"
替换为
Call newWorkbook.PartEntryShow

© www.soinside.com 2019 - 2024. All rights reserved.