我有小时数据,当我尝试执行以下代码时,我收到运行时错误91.我在CYC表中的数据格式例如是#07/07/2009 23:00:00#(at第194行,但是当我输入它时它会自动将其转换为#7/7/2009 11:00:00 PM#。 (请注意,已声明并设置了shtCYC和shtCo)。
Dim dt As Date
dt = #7/7/2009 11:00:00 PM#
Do
shtCYC.Activate
'finds the day
Set rng = shtCYC.Range("A3:A1514").Find(dt, , xlValues)
'copies the dates
shtCYC.Range("A" & rng.Row - 191 & ":A" & rng.Row + 24).Copy (this is where the debug highlights)
shtCO.Range("B10").PasteSpecial Paste:=xlPasteValues
任何人有任何想法..? 非常感谢!
答案 0 :(得分:4)
那不是我看到的唯一问题。请参阅下面的代码。
rng.Row
是否属于特定范围我在评论中已经解释过了。如果您还有疑问,请与我联系。
Sub Sample()
Dim dt As Date
Dim shtCYC As Worksheet
Dim Rng As Range
dt = #7/7/2009 11:00:00 PM#
Set shtCYC = ActiveSheet '<~~ Change this to the relevant sheet
With shtCYC
Set Rng = .Range("A3:A1514").Find(what:=DateValue(dt), LookIn:=xlFormulas)
'~~> Check If match found
If Not Rng Is Nothing Then
'~~> This Check is required because what if the rng.row is <=191 or >=1048552?
'~~> I understand that you have mentioned the range as "A3:A1514"
'~~> But tom if you use .Cells then?
'~~> Rng.Row - 191 / Rng.Row + 24 will give you error in that case
If Rng.Row > 191 Or Rng.Row < (.Rows.Count - 24) Then
.Range("A" & Rng.Row - 191 & ":A" & Rng.Row + 24).Copy
'shtCO.Range("B10").PasteSpecial Paste:=xlPasteValues
End If
Else
MsgBox "Match Not Found"
End If
End With
End Sub
在Excel 2013中测试过。我的工作表看起来像这样。
答案 1 :(得分:0)
使用工作表MATCH function找到日期时间可能会更成功。在搜索包含时间的值时,我经常遇到Range.Find method的问题。
Dim dt As Date, rw As Variant
Dim shtCYC As Worksheet, shtCO As Worksheet
dt = #7/7/2009 11:00:00 PM#
Debug.Print dt
Set shtCYC = Worksheets("Sheet4") '<~~ set the source worksheet
Set shtCO = Worksheets("Sheet5") '<~~ set the target worksheet
With shtCYC
'finds the row containing the datetime value
rw = Application.Match(CDbl(dt), .Columns(1), 0)
If Not IsError(rw) Then
'dt was found, transfer the block of values
If rw > 194 Then
shtCO.Range("B10").Resize(216, 1) = _
.Cells(rw, 1).Resize(216, 1).Value
Else
Debug.Print rw & " not large enough to encompass all values."
End If
Else
Debug.Print dt & " not found."
End If
End With
请注意,这是使用直接价值转移而非Copy&amp;糊。它是一种更有效的传递xlPasteValues的方法,因为它不涉及剪贴板。