繁体   English   中英

使用输入框将另一个工作簿引用到子

[英]Use input box to reference another workbook into sub

我整理了一个子文件,它允许您输入要子文件引用的文件名,而不是对单个文件进行编码。 但是在输入框之外,我收到错误“下标超出范围”。 我尝试输入带有和不带有“”和文件扩展名 .xls 的文件名

Sub tester()

Dim wbName As String
wbName = Application.InputBox("What is the workbook name?")
If Right(wbName, 4) <> ".xls" Then wbName = wbName + ".xls"
Set mainWB = Workbooks(wbName)

Dim copyThis As Range, pasteThis As Range

Set copyThis = mainWB.Worksheets(2).Columns("F")
Set pasteThis = Workbooks("VBA Workbook.xlsm").Worksheeets(1).Columns("A")

copyThis.Copy Destination:=pasteThis

End Sub

每当有用户干预时,您将不得不使用大量错误处理来避免可能的错误。 我recommned使用Userform insetad。 而不是创建用户,键入工作簿名称,使用带有所有打开工作簿名称的ComboBox1如下图所示)的UserForm ,以便用户可以选择相关工作簿而不是键入名称

在此处输入图片说明

代码

Option Explicit

Private Sub UserForm_Initialize()
    Dim wkb As Workbook
    Me.Label1.Caption = "Please select the relevant workbook"
    With Me.ComboBox1
        '~~> Loop thorugh all open workbooks and add
        '~~> their name to the Combobox
        For Each wkb In Application.Workbooks
            .AddItem wkb.Name
        Next wkb
    End With
End Sub

Private Sub CommandButton1_Click()
    If ComboBox1.ListIndex = -1 Then
        MsgBox "Please select a wotkbook name and try again"
        Exit Sub
    End If

    Dim wb As Workbook

    Set wb = Workbooks(ComboBox1.List(ComboBox1.ListIndex))

    With wb
        MsgBox .FullName

        '~~> Do what you want
    End With
End Sub

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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