我在VBA中编写了一个简单的模块,当它保存为宏时工作正常但是当我将其保存为加载项并运行时,它表现得很奇怪。 它给出错误:对象“表格”的方法“移动”失败 然后从文件编号1打开工作表(代码中x = 1)。
谢谢大家的帮助。我没有尝试使用其他系统检查我的MS Excel中的安全问题,但我没有锁定代码或表格通过密码。
代码:
Sub opensheets()
Dim openfiles
Dim x As Integer
On Error GoTo ErrHandler
Application.ScreenUpdating = False
openfiles = Application.GetOpenFilename _
(FileFilter:="Microsoft Excel Files (*.xls;*.xlsx),*.xls;*.xlsx", _
MultiSelect:=True, Title:="Select Excel files!")
If TypeName(openfiles) = "Boolean" Then
MsgBox "You need to select atleast one file"
GoTo ExitHandler
End If
x = 1
While x <= UBound(openfiles)
Workbooks.Open Filename:=openfiles(x)
Sheets().Move After:=ThisWorkbook.Sheets _
(ThisWorkbook.Sheets.Count)
x = x + 1
Wend
ExitHandler:
Application.ScreenUpdating = True
Exit Sub
ErrHandler:
MsgBox Err.Description
Resume ExitHandler
End Sub
答案 0 :(得分:0)
如果您尝试从另一本书中获取所有工作表并将其移至当前工作簿的末尾(包含代码的那本),那么这对我有用:
...
While x <= UBound(openfiles)
Dim wb as Workbook
Set wb = Workbooks.Open(Filename:=openfiles(x))
wb.Sheets().Move After:=ThisWorkbook.Sheets _
(ThisWorkbook.Sheets.Count)
x = x + 1
Wend
...
如果您正在寻找其他内容,请澄清您的问题。
答案 1 :(得分:0)
如果您的代码在加载项中运行,ThisWorkbook
指的是加载项。相反,您可能希望明确引用刚刚打开的工作簿。也许是这样的:
Dim wkb As Workbook
While x <= UBound(openfiles)
Set wkb = Workbooks.Open(Filename:=openfiles(x))
Sheets().Move After:=wkb.Sheets(wkb.Sheets.Count)
x = x + 1
Wend