[英]Range(cells(x,y)).copy Throwing Error 1004
我有一个每天必须导出的工作表,其中包含工作时间表。 我想要做的是在将 .csv 文件中的数据复制到我的工作簿之前对其进行操作。 对于任何一天,技术人员最多可以有 1 天的 4 个时间表。 我试图找到常规班次所在的列并将其移动到 E 列。
| Supervisor | Technician | On Duty? | Earliest Route Time | Shift 1 Type | Shift 1 Start | Shift 1 End | Shift 2 Type | Shift 2 Start | Shift 2 End |
|------------|------------|----------|---------------------|--------------|---------------|-------------|--------------|---------------|-------------|
| Harold | Doug | No | | Meetings | 8:00 AM | 9:30 AM | Regular | 9:30 AM | 4:30 PM |
| Harold | Greg | No | | Meetings | 8:00 AM | 9:30 AM | Regular | 9:00 AM | 4:30 PM |
| | | | | | | | | | |
我试图从( 为什么 Range 工作,而不是 Cells? )实施解决方案,还有另一个解决方案,但我似乎已经失去了它。
Sub test_cell()
Dim sh1 As Worksheet
Dim x as Integer
Dim col as Integer
For Each w In Workbooks 'loop through open workbooks
If w.Name = "tech_shifts_now.csv" Then
w.Activate
Sheets("tech_shifts_now").Select
Set sh1 = ActiveWorkbook.Sheets("tech_shifts_now")
x = 3
If Cells(x, 5) <> "Regular" Then
With sh1
.Range(.Cells(x, 5), .Cells(x, 7)).Copy Destination:=.Range(.Cells(x, 17)) 'Move current data to Q
End With
'Range("E" & x & ":G" & x).Copy Range("Q" & x)
'Find the column that regular shift is in
Rows(x).Find(What:="Regular", LookIn:=xlFormulas, _
LookAt:=xlPart, SearchOrder:=xlByRows, SearchDirection:=xlNext, _
MatchCase:=False, SearchFormat:=False).Activate
'get the columns number
col = ActiveCell.Column
'copy the data for regular to Column E
Range(Cells(x, col), Cells(x, col + 2)).Copy Destination:=Range(Cells(x, 5))
'Copy for Column Q to where we just removed the Regular data from
Range("Q" & x & ":S" & x).Copy Range(Cells(x, col))
End If
End If
Next w
End Sub
当它到达.Range(.Cells(x, 5), .Cells(x, 7)).Copy Destination:=.Range(.Cells(x, 17))
时,我收到error 1004 Method Range of Object _worksheet failed
你的目的地错了。 它应该只是.Cells(x, 17)
。 或者, .Range(.Cells(x, 17).Address)
。
Range(Cells(x, col), Cells(x, col + 2)).Copy Destination:=.Cells(x, 17)
为什么? Range
对象至少有两个未明确调用的构造函数。 如果您使用单个参数调用Range
,则假定为(强调):
使用
Range(arg)
,其中arg
命名范围,返回代表单个单元格或单元格范围的 Range 对象
这里, Range(<something>)
需要一个标识范围的字符串,如Range("A2")
或Range("Some_Named_Range")
等。
当你通过Range(Cells(1,1))
,内部部分( Cells(1,1)
,它本身就是一个Range
)被评估。 由于单单元格Range
可以(通常)从其Value
属性隐式转换为String
,但由于这不是(通常)有效引用,因此会发生错误。
如前所述,你可以这样做: Range(Cells(1,1).Address)
但我认为这有点难看,即使有效。
Range
确实有一个接受两个Range
参数的构造函数,但是您将Range
对象传递给需要一个String
参数的构造函数。 隐式转换发生在幕后,您会遇到难以解决的错误:)
使用
Range(cell1, cell2)
其中cell1
和cell2
的Range
对象指定的开始和结束的细胞,返回一个Range对象
按照这个逻辑,你实际上可以做Range(Cells(1,1), Cells(1,1))
,但同样,不必要的冗长/重复,我不喜欢这个约定。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.