Worksheets("Hello").Move After:=Workbooks("FILE2").Sheets(1)
我有两个打开的活动文件。 Hello.xlsb和FILE2.xlsb
以上代码仅适用于我的计算机,但不适用于共享驱动器。 我收到"下标超出范围错误"。
我们需要指定扩展名FILE2.xlsb才能使其正常工作。
但是,我希望这适用于任何具有任何扩展名的FILE2。 如何做到这一点?
答案 0 :(得分:0)
此代码会要求您打开目标工作簿并将工作表移入其中,这是您所追求的吗?
Public Sub Test()
Dim vfile As Variant
Dim wrkBk As Workbook
'Ask for the location of File2.
vfile = GetFile(ThisWorkbook.Path)
Set wrkBk = Workbooks.Open(vfile)
ThisWorkbook.Worksheets("Hello").Move After:=wrkBk.Worksheets(1)
End Sub
Function GetFile(Optional startFolder As Variant = -1) As Variant
Dim fle As FileDialog
Dim vItem As Variant
Set fle = Application.FileDialog(msoFileDialogFilePicker)
With fle
.Title = "Select a File"
.AllowMultiSelect = False
.Filters.Add "Excel Files", "*.xls*", 1
If startFolder = -1 Then
.InitialFileName = Application.DefaultFilePath
Else
If Right(startFolder, 1) <> "\" Then
.InitialFileName = startFolder & "\"
Else
.InitialFileName = startFolder
End If
End If
If .Show <> -1 Then GoTo NextCode
vItem = .SelectedItems(1)
End With
NextCode:
GetFile = vItem
Set fle = Nothing
End Function
答案 1 :(得分:0)
如果您的目标工作簿已经打开,那么无论扩展名如何,您都可以使用它来安全地引用工作簿:
Dim destWb As Workbook
Set destWb = GetWb("file2")
if destWb Is Nothing then
Msgbox "destination file not open!"
else
'perform the copy
end if
用法
regexp_substr()
仅供参考,这可能是您看到计算机之间差异的原因: