在将工作表复制到另一个工作簿时,我遇到了类似的问题。我更喜欢避免使用“activesheet”,因为它在过去给我带来了问题。因此,我编写了一个函数来根据我的需要执行此操作。我在这里为那些像我一样通过谷歌到达的人添加它:
这里的主要问题是将可见工作表复制到最后一个索引位置会导致 Excel 将工作表重新定位到可见工作表的末尾。因此,将工作表复制到最后一张可见工作表之后的位置可以解决此问题。即使您正在复制隐藏的工作表。
Function Copy_WS_to_NewWB(WB As Workbook, WS As Worksheet) As Worksheet
'Creates a copy of the specified worksheet in the specified workbook
' Accomodates the fact that there may be hidden sheets in the workbook
Dim WSInd As Integer: WSInd = 1
Dim CWS As Worksheet
'Determine the index of the last visible worksheet
For Each CWS In WB.Worksheets
If CWS.Visible Then If CWS.Index > WSInd Then WSInd = CWS.Index
Next CWS
WS.Copy after:=WB.Worksheets(WSInd)
Set Copy_WS_to_NewWB = WB.Worksheets(WSInd + 1)
End Function
要将此功能用于原始问题(即在同一工作簿中),可以使用类似...
Set test = Copy_WS_to_NewWB(Workbooks(1), Workbooks(1).Worksheets(1))
test.name = "test sheet name"
EDIT 04/11/2020 from –user3598756 添加对上述代码的轻微重构
Function CopySheetToWorkBook(targetWb As Workbook, shToBeCopied As Worksheet, copiedSh As Worksheet) As Boolean
'Creates a copy of the specified worksheet in the specified workbook
' Accomodates the fact that there may be hidden sheets in the workbook
Dim lastVisibleShIndex As Long
Dim iSh As Long
On Error GoTo SafeExit
With targetWb
'Determine the index of the last visible worksheet
For iSh = .Sheets.Count To 1 Step -1
If .Sheets(iSh).Visible Then
lastVisibleShIndex = iSh
Exit For
End If
Next
shToBeCopied.Copy after:=.Sheets(lastVisibleShIndex)
Set copiedSh = .Sheets(lastVisibleShIndex + 1)
End With
CopySheetToWorkBook = True
Exit Function
SafeExit:
End Function
除了使用不同的(更具描述性的?)变量名之外,重构主要处理:
将函数类型转换为布尔值,同时在函数参数中包含返回的(复制的)工作表列出这个,让调用子处理可能的错误,比如
Dim WB as Workbook: Set WB = ThisWorkbook ' as an example
Dim sh as Worksheet: Set sh = ActiveSheet ' as an example
Dim copiedSh as Worksheet
If CopySheetToWorkBook(WB, sh, copiedSh) Then
' go on with your copiedSh sheet
Else
Msgbox "Error while trying to copy '" & sh.Name & "'" & vbcrlf & err.Description
End If
让 For - Next 循环从最后一个工作表索引向后步进并在第一个可见工作表出现时退出,因为我们在“最后一个”可见工作表之后