vba - 复制工作表粘贴为值但跳过受保护的单元格
问题描述
我正在循环浏览几张纸,并想删除我不想要的那些。对于我想保留的那些,我正在复制所有内容并粘贴为值。问题是有一些我无法保护的受保护单元格,这给了我一个错误。如何避免?
Sub save()
Dim wb As Workbook
Dim path As String
Dim fname As String
Dim fdate As Date
' picks up the date of the reporting period so it uses it for naming the new workbook
fdate = Sheets("Instructions").Range("D1").Value
Sheets("Introduction").Range("F9").Copy
Sheets("Introduction").Range("F9").PasteSpecial xlPasteValues
Sheets("Introduction").Range("F10").Copy
Sheets("Introduction").Range("F10").PasteSpecial xlPasteValues
Application.DisplayAlerts = False
'FOR EACH SHEET IN THE WORKBOOK THAT IS ONE OF THE 5 ONES WE WANT TO SAVE IS COPIES AND PASTES AS VALUES AND DELETES THE ONES THAT ARE NOT NAMES AS BELOW
For Each Sheet In ActiveWorkbook.Sheets
If Sheet.Name = "Introduction" Or Sheet.Name = "Instructions" Or Sheet.Name = "Results" Then
Sheet.Select
Cells.Select
Selection.Copy
Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
:=False, Transpose:=False
Selection.Locked = True
Sheet.Range("D2") = fdate
ActiveSheet.Protect Password:="password", DrawingObjects:=True, Contents:=True, Scenarios:=True
Else
'if sheet is not one of the X it gets deleted
Sheet.Delete
End If
Next
' adding the name we wish to give the new workbook
fname = Sheets("Introduction").Range("F7") & "Result" & fdate
path = Application.ActiveWorkbook.path
'ActiveWorkbook.Protect Password:="password", Structure:=True, Windows:=False
'saves the workbook as the name we chose and date
Application.ActiveWorkbook.SaveAs Filename:=path & "\" & fname, _
FileFormat:=xlOpenXMLWorkbook, CreateBackup:=False
'close the workbook
ActiveWindow.Close
Application.DisplayAlerts = True
End Sub
我尝试了一些代码,例如:
for each cell in sheet
if Not cell.Locked then
cell.copy
cell.pastespecial xlpastevalues
end if
next
但不工作,它给了我一个错误,“对于工作表中的每个单元格”错误 438,即未定义对象或类似的东西。
有什么建议么?
解决方案
缺少单元格的声明,接下来您需要工作表中的一个范围来循环遍历(.UsedRange 循环遍历工作表中所有使用的单元格)。这应该有效:
Dim cell As Range
for each cell in sheet.UsedRange
if Not cell.Locked then
cell.copy
cell.pastespecial xlpastevalues
end if
next
推荐阅读
- python - 如何将 Excel 工作表中的数据放入具有多个参数的 API 链接并使用 Python 下载 PDF?
- php - 网站中的错误调用函数 Cookie Alert
- javascript - React Bootstrap 组件在部署到 Heroku 时不显示
- elasticsearch - Elasticsearch 中的 Maps 与 Lists 以优化查询性能
- php - Yii2 Active Record 'with' 关系不返回子数据
- wso2 - WSO2 V3.0 CORS 问题
- php - WooCommerce 插件:在 WordPress 网站上安装未创建运行所需的表
- amazon-web-services - 如何多次部署 AWS CDK 应用程序?
- c++ - 如何在 C++ 中读取带有逗号分隔值的流?
- exception - 关于在 Ocaml 的 for 循环中间引发异常