gpt4 book ai didi

vba - 复制整个工作表并粘贴为值

转载 作者:行者123 更新时间:2023-12-02 00:33:29 25 4
gpt4 key购买 nike

我正在尝试将事件工作表复制到新工作簿中,然后保存该新工作簿并关闭它。这是通过单击事件工作表中的表单(按钮)来触发的。然后,在保存之前,该按钮会在新工作簿中删除。

我正在事件工作表中使用公式。我试图仅复制值和任何其他格式。

新工作簿不显示值,而仅显示空单元格(也没有显示公式,这当然可以)。具体来说,当复制具有间接公式的单元格时,似乎会出现此问题;对于使用对原始工作簿中其他工作表的更简单引用的单元格来说,这似乎没有问题。

代码如下:

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

最佳答案

这是一种略有不同的方法。

逻辑:

  1. 在用户的临时目录中创建事件工作簿的副本
  2. 打开副本
  3. 将公式更改为值。其余格式保持不变。
  4. 删除所有不需要的工作表
  5. 删除不必要的形状。

代码:(经过尝试和测试)

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

关于vba - 复制整个工作表并粘贴为值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19400024/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com