我正在尝试将活动工作表复制到新工作簿中,然后保存该新工作簿并将其关闭。通过单击活动工作表中的表单(按钮)来触发此操作。然后在保存之前,在新工作簿中删除该按钮。
我在活动工作表中使用公式。我正在尝试仅复制值和任何其他格式。
新工作簿不显示值,而是仅显示空单元格(不显示任何公式,当然可以)。具体来说,当使用间接公式复制单元格时,似乎会出现问题。对于在原始工作簿中使用对其他工作表的简单引用的单元格似乎没有问题。
以下是代码:
Sub CopyRemoveFormAndSave()
Dim RelativePath As String
Dim shp As Shape
Dim testStr As String
' Copy and Paste Active Sheet
ActiveSheet.Copy
With ActiveSheet.UsedRange
.Value = .Value
End With
' Remove forms
For Each shp In ActiveSheet.Shapes
If shp.Type = 8 Then
If shp.FormControlType = 0 Then
testStr = ""
On Error Resume Next
testStr = shp.TopLeftCell.Address
On Error GoTo 0
If testStr <> "" Then shp.Delete
Else
shp.Delete
End If
End If
Next shp
' Save New Workbook and Close
Application.DisplayAlerts = False
RelativePath = ThisWorkbook.Path & "\" & ActiveSheet.Name & "_Reporting_" & Format(Now, "yymmdd") & ".xlsx"
ActiveWorkbook.SaveAs Filename:=RelativePath
ActiveWorkbook.Close
Application.DisplayAlerts = True
End Sub
答案 0 :(得分:3)
这是一种略有不同的方法。
<强>逻辑:强>
代码:(经过测试和测试)
Private Declare Function GetTempPath Lib "kernel32" Alias "GetTempPathA" _
(ByVal nBufferLength As Long, ByVal lpBuffer As String) As Long
Private Const MAX_PATH As Long = 260
'~~> Function to get user's temp directoy
Function TempPath() As String
TempPath = String$(MAX_PATH, Chr$(0))
GetTempPath MAX_PATH, TempPath
TempPath = Replace(TempPath, Chr$(0), "")
End Function
Sub CopyRemoveFormAndSave()
Dim wb As Workbook, wbNew As Workbook
Dim ws As Worksheet
Dim wsName As String, NewName As String
Dim shp As Shape
Set wb = ThisWorkbook
wsName = ActiveSheet.Name
NewName = wsName & ".xlsm"
wb.SaveCopyAs TempPath & NewName
Set wbNew = Workbooks.Open(TempPath & NewName)
wbNew.Sheets(wsName).UsedRange.Value = wbNew.Sheets(wsName).UsedRange.Value
Application.DisplayAlerts = False
For Each ws In wbNew.Worksheets
If ws.Name <> wsName Then ws.Delete
Next ws
Application.DisplayAlerts = True
For Each shp In wbNew.Sheets(wsName).Shapes
If shp.Type = 8 Then shp.Delete
Next
'
'~~> Do a save as for the new workbook if required.
'
End Sub
答案 1 :(得分:2)