【发布时间】:2014-12-04 09:16:51
【问题描述】:
下面是将动态数据范围从 Sheet1 复制到 Sheet2 的子程序(后者是受密码保护的工作表)。
除了 lRowSh2 和 lColSh2 在 Sheet2 完全空白时会导致严重错误之外,它工作得很好。
我是否可以使用某种If 语句,以便在单元格为空白时跳过清除 Sheet2 的部分(注意:它们过去可能有值)?
为清楚起见,第 6 行是两个工作表中的标题行。
Sub CopyData()
Application.ScreenUpdating = False
Dim lRowSh1 As Long, lColSh1 As Long, lRowSh2 As Long, lColSh2 As Long
Dim Sheet1Data() As Variant
' Warning message before proceeding with data transfer to sample selection worksheet.
If MsgBox("Copy data to Sheet2? (this will overwrite existing data in Sheet2)", _
vbYesNo + vbCritical) = vbYes _
Then
With Sheets("Sheet1")
' Determines last row and column of Sheet1 data range.
lRowSh1 = .Cells.Find("*", .Cells(1, 1), , , xlByRows, xlPrevious).Row
lColSh1 = .Cells.Find("*", .Cells(1, 1), , , xlByColumns, xlPrevious).Column
' Loads Sheet1 data range (row 6 to last row for all columns) into array Sheet1Data.
Sheet1Data = .Range(.Cells(6, 1), .Cells(lRowSh1, lColSh1)).Value
End With
With Sheets("Sheet2")
' Lifts worksheet protection for execution of code
.Unprotect Password:="admin"
' Removes any existing filters in Sheet2.
If .AutoFilterMode = True Then .AutoFilter.ShowAllData
' Determines last row and column of any pre-existing data in Sheet2 and clears:
lRowSh2 = .Cells.Find("*", .Cells(1, 1), , , xlByRows, xlPrevious).Row
lColSh2 = .Cells.Find("*", .Cells(1, 1), , , xlByColumns, xlPrevious).Column
.Range(.Cells(6, 1), .Cells(lRowSh2, lColSh2)).ClearContents
' Repopulates with the contents of array Sheet1Data:
.Range(.Cells(6, 2), .Cells(lRowSh1, lColSh1 + 1)).Value = Sheet1Data
' Autofit repopulated columns:
.Cells.EntireColumn.AutoFit
' Reapply AutoFilter to header (Row 6):
.Cells(6, 1) = " "
.Cells(6, 1).EntireRow.AutoFilter
' Reapply worksheet protection after execution of code:
.Protect Password:="admin", userinterfaceonly:=True, AllowFiltering:=True
.EnableSelection = xlNoRestrictions
End With
End If
Application.ScreenUpdating = True
End Sub
【问题讨论】:
-
要检查一个范围是否为空,你可以使用
CountA,类似的答案在这里:stackoverflow.com/questions/10811121/… -
查找返回一个范围。如果 Find 失败,该 Range 的值将为 Nothing。没有任何东西没有属性或行或列,因此会出现错误。试试
Dim Rng as RangeRng= ...Find...If Rng Is Nothing Then' Empty sheet... -
谢谢大家,工作正常!与往常一样,感谢托尼的“为什么”:) 如果您将回复粘贴为回复,我会接受。
-
我已按照您的建议发布了答案。感谢您要求我这样做。顺便说一句,只有问题或答案的作者会被自动告知 cmets。对于其他所有人,如果您想告知
Name,则需要在评论中包含@Name。 -
一直想知道该怎么做,非常感谢:)