使用文件对话框选取器从Excel工作表中获取工作表名称

时间:2015-11-05 11:52:56

标签: vba excel-vba excel

我有要求,我需要从已关闭的Excel文件中获取工作表名称并将其粘贴到活动工作簿的“Sheet1”列“A”上。

目前我正在使用此代码,但是当我尝试通过Addin运行时似乎失败了。如果我将此代码粘贴到当前工作簿模块中,此代码工作正常。

请告知。

Sub GetTables()
Dim directory As String, file As String, sheet As Worksheet, fd As Office.FileDialog, wb As Workbook
Dim lastrow As Long

Set fd = Application.FileDialog(msoFileDialogFilePicker)


With fd
.InitialFileName = "C:\data\Table Updates"
.AllowMultiSelect = True
.Title = "Please select the file to get the records..."
.Filters.Clear
.Filters.Add "Excel 2003", "*.xls?"


If .Show = True Then
file = Dir(.SelectedItems(1))
End If
End With


Application.ScreenUpdating = False
Application.DisplayAlerts = False


GetSheetsNames (file)
'Workbooks.Open (fileName)


End Sub


Function GetSheetsNames(file)
Dim lastrow As Long, c As Variant
lastrow = 1
Set sh = GetObject(file).Worksheets

For Each c In sh

ActiveWorkbook.Worksheets("Sheet1").Cells(lastrow, 1) = c.Name
    ActiveWorkbook.Worksheets("Sheet1").Cells(lastrow, 1) = Trim(ActiveWorkbook.Worksheets("Sheet1").Cells(lastrow, 1))
    lastrow = ActiveWorkbook.Worksheets("Sheet1").Range("A1").CurrentRegion.Rows.Count + 1
    MsgBox (c.Name)
    Application.ScreenUpdating = True
Application.DisplayAlerts = True
Next
End Function

0 个答案:

没有答案