打开文件,选择工作表并将其复制到带有宏的文件中

时间:2019-06-14 10:33:52

标签: excel vba

这是我的第一篇文章。我想要一个代码,该代码允许用户选择带有filedialog的文件,然后将文件中的工作表名称填充到用户窗体,然后使用该代码将所选工作表复制到工作簿中。

Private wbSource As Workbook
Private wsSource As Worksheet

Private Sub UserForm_Initialize()

Dim I As Long
Dim filedlg As FileDialog

Set filedlg = Application.FileDialog(msoFileDialogFilePicker)
    With filedlg
        .Title = "Please select a file to list Sheets from"
        .InitialFileName = ThisWorkbook.Path
        .ButtonName = "Select"
        If .Show <> -1 Then End
    End With

Set wbSource = Workbooks.Open(filedlg.SelectedItems(1))

Me.ComboBox1.Clear
    With wbSource
        For I = 1 To .Worksheets.Count
            Me.ComboBox1.AddItem Sheets(I).Name
        Next
    End With
End Sub

Private Sub ComboBox1_Click()

Set wsSource = wbSource.Worksheets(Me.ComboBox1.Value)

wsSource.Copy ThisWorkbook.Sheets(Sheets.Count)
wbSource.Close SaveChanges:=False

Unload Me
End Sub

代码将一直有效,直到excel尝试复制工作表为止,并且出现运行时错误9-下标超出范围。我是否错误地声明了变量?

0 个答案:

没有答案