亲爱的Stackoverflow成员,
过去我在堆栈溢出的帮助下创建了一个动态导入脚本。此脚本从文件夹中的工作簿导入所有工作表。
但是现在我只想导入名为'sheet1'的工作表,而不是工作簿中的所有工作表(工作表1,2和3)。
我试图略微修改'worksheets'变量,但我无法让它工作。
代码由宏脚本和函数组成: 这是Sub
Public Sub Import_sheets_from_dir()
' Import script from http://www.excel-easy.com/vba/examples/import-sheets.html
' Function script from http://stackoverflow.com/questions/19372319/vba-folder-picker-set-where-to-start
On Error GoTo ErrMsg
Dim directory As String
Dim fileName As String
Dim Sheet As Worksheet
Set ActivoWB = ActiveWorkbook
Application.ScreenUpdating = False
Application.DisplayAlerts = False
directory = GetFolderName() & "/"
fileName = Dir(directory & "*.xl??")
Do While fileName <> ""
Workbooks.Open (directory & fileName)
For Each Sheet In Workbooks(fileName).Worksheets
Workbooks(fileName).Worksheets(Sheet.Name).Copy _
After:=ActivoWB.Sheets(ActivoWB.Sheets.Count)
Next Sheet
Workbooks(fileName).Close
fileName = Dir()
Loop
Application.ScreenUpdating = True
Application.DisplayAlerts = True
Exit Sub
ErrMsg:
MsgBox prompt:="your doing something wrong"
End Sub
这是使用过的功能:
Public Function GetFolderName(Optional OpenAt As String) As String
Dim lCount As Long
GetFolderName = vbNullString
With Application.FileDialog(msoFileDialogFolderPicker)
.InitialFileName = OpenAt
.Show
For lCount = 1 To .SelectedItems.Count
GetFolderName = .SelectedItems(lCount)
Next lCount
End With
End Function
我也想知道哪个名称与更改更相关,我想使用VBA名称(红色,而不是蓝色(在Excel中显示的工作表名称))。 Print Screen from VBA window 我想了解两者编码的区别。
我尝试修改循环For Each Sheet In Workbooks(fileName).Sheet1
,但这不起作用。
你能指导我正确的方向吗?
提前致谢!
此致 Dubblej
答案 0 :(得分:0)
不能这么简单:
For Each Sheet In Workbooks(fileName).Worksheets
If (Sheet.Name = "Sheet1") Then
Sheet.Copy _
After:=ActivoWB.Sheets(ActivoWB.Sheets.Count)
Endif
Next Sheet