Excel中的这个VBA脚本在'ThisWorkbook'
中输入时效果很好,但是当我在特定的工作表中输入它时(我想将它链接到一个按钮),它不起作用,它会出错在这一行:
ActiveSheet.Range(Cells(intStartRow, cell.Column), Cells(lonLowRow, cell.Column)).NumberFormat = "m/d/yyyy"
The error given is: 1004
有人知道为什么以及如何补救它? 谢谢!!
Sub proefje()
Dim strTitleRow As String
Dim arrDates() As String
Dim arrTimes() As String
Dim intStartRow As Integer
Dim lonLowRow As Long
strTitleRow = "D5:AW5"
arrDates = Split("Last update,Last recovery test,Date installed,Key valid until", ",")
arrTimes = Split("Time", ",")
intStartRow = 6
lonLowRow = ActiveSheet.Range("BB3").Value + ActiveSheet.Range("BE3").Value
'Date/Time job start
ActiveSheet.Range(strTitleRow).Select
For Each cell In Selection
If IsInArray(cell.Value, arrDates) Then
ActiveSheet.Range(Cells(intStartRow, cell.Column), Cells(lonLowRow, cell.Column)).NumberFormat = "m/d/yyyy"
End If
If IsInArray(cell.Value, arrTimes) Then
ActiveSheet.Range(Cells(intStartRow, cell.Column), Cells(lonLowRow, cell.Column)).NumberFormat = "[$-F400]h:mm:ss AM/PM"
End If
Next cell
End Sub
Function IsInArray(stringToBeFound As String, arr As Variant) As Boolean
IsInArray = (UBound(Filter(arr, stringToBeFound)) > -1)
End Function
答案 0 :(得分:2)
在Worksheet模块的上下文中,Cells
对象(除非另有限定)引用Me.Cells
,即代码所在的工作表。请参阅我放在Sheet1
模块中的这个简单示例,当Sheet2是ActiveSheet时,它将引发1004错误。
Sub sheet1Macro()
MsgBox ActiveSheet.Range(Cells(1, 1), Cells(1, 2)).Address
End Sub
你有一个这样的结构,它使用ActiveSheet
,它可能(或可能不是)是同一张纸。如果Me
和ActiveSheet
不是同一个工作表,则会出现错误,因为您无法定义跨越多个工作表的范围。
ActiveSheet.Range(Cells(intStartRow, cell.Column), Cells(lonLowRow, cell.Column)).NumberFormat = "m/d/yyyy"
End If
解决方案:将代码放入标准模块中,或完全限定您的范围对象,例如:
With ActiveSheet
.Range(.Cells(intStartRow, cell.Column), .Cells(lonLowRow, cell.Column)).NumberFormat = "m/d/yyyy"
End With
进一步阅读: