[英]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.