【发布时间】:2018-01-25 02:14:45
【问题描述】:
我能够利用其他人的代码从外部工作簿导入工作表,但是代码需要我手动更改工作表名称。
我目前在工作簿 A 中有一个列,其中包含我试图从工作簿 B(有数百个工作表)中提取的每个(大约 20 个)工作表的名称。有没有办法循环此代码并引用工作簿 A 中的列来更改要从工作簿 B 中提取的宏中的工作表名称? 下面的代码(假设 WORKSHEET1 是我从工作簿 B 中提取的工作表的名称)
Sub ImportSheet()
Dim sImportFile As String, sFile As String
Dim sThisBk As Workbook
Dim vfilename As Variant
Application.ScreenUpdating = False
Application.DisplayAlerts = False
Set sThisBk = ActiveWorkbook
sImportFile = Application.GetOpenFilename( _
FileFilter:="Microsoft Excel Workbooks, *.xls; *.xlsx", Title:="Open Workbook")
If sImportFile = "False" Then
MsgBox "No File Selected!"
Exit Sub
Else
vfilename = Split(sImportFile, "\")
sFile = vfilename(UBound(vfilename))
Application.Workbooks.Open Filename:=sImportFile
Set wbBk = Workbooks(sFile)
With wbBk
If SheetExists("WORKSHEET1") Then
Set wsSht = .Sheets("WORKSHEET1")
wsSht.Copy before:=sThisBk.Sheets("Sheet1")
Else
MsgBox "There is no sheet with name :WORKSHEET1 in:" & vbCr & .Name
End If
wbBk.Close SaveChanges:=False
End With
End If
Application.ScreenUpdating = True
Application.DisplayAlerts = True
End Sub
Private Function SheetExists(sWSName As String) As Boolean
Dim ws As Worksheet
On Error Resume Next
Set ws = Worksheets(sWSName)
If Not ws Is Nothing Then SheetExists = True
结束函数
【问题讨论】:
标签: vba excel import import-from-excel