我一直试图将数据从源文件表复制到目标文件表。目标文件表包含该宏。但是在选择源工作表文件中的数据范围时,我总是遇到错误。有人可以帮忙纠正此行的错误吗? 设置srcData = sourceSht.Range(StartCell&“:”&sourceSht.Cells(lRow,lCol))。选择
' Open file
wbkName = ThisWorkbook.Name ' this workbook is the macro workbook file
filePath = Sheet29.Range("D2").Value 'this contains filepath of source workbook
Set sourceSht = Sheet29.Range("C12") ' this contains name of sheet of source workbook
Set wbk = Workbooks.Open(filePath)
' Copy source file contents
Set StartCell = sourceSht.Range("A1")
lRow = sourceSht.Cells(sourceSht.Rows.Count, StartCell.Column).End(xlUp).Row 'select last row value
lCol = sourceSht.Cells(StartCell.Row, sourceSht.Columns.Count).End(xlToLeft).Column 'select last column value
Set srcData = sourceSht.Range(StartCell & ":" & sourceSht.Cells(lRow, lCol)).Select
srcData.Copy
'Paste data to destination macro sheet
wbkName.Active
Sheets("CopyMacro").Range("E14").Value
srcData.paste
答案 0 :(得分:1)
范围的默认属性是.Value
,所以当您说.Range(StartCell & ":"...
时,您不是在寻址单元格地址,而是它的值。试试这个
Set srcData = sourceSht.Range(startCell.Address & ":" & sourceSht.Cells(lRow, lCol).Address)
然后您可以将该范围用作
With srcData
'~~> Do what you want
End With
顺便说一句,您的代码也可以写为
Set srcData = sourceSht.Range("A1:" & Cells(lRow, lCol).Address)
With srcData
.Copy
wbkName.Sheets("CopyMacro").Range("E14").PasteSpecial _
Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks:=False, Transpose:=False
End With
请注意,我们使用Cells(lRow, lCol).Address
而不是sourceSht.Cells(lRow, lCol).Address
。不需要,因为工作表中的地址将相同。它将返回一个字符串。例如Set srcData = sourceSht.Range("A1:" & "$C$10")
答案 1 :(得分:0)
设置范围时,您无需Select
。
您必须从以下行中删除.Select
...
Set srcData = sourceSht.Range(StartCell & ":" & sourceSht.Cells(lRow, lCol)).Select
您还可以如下设置范围...
Set srcData = sourceSht.Range(StartCell, sourceSht.Cells(lRow, lCol))
然后您可以copy and paste
srcData
,而无需像下面那样激活wbkName
工作簿...
srcData.Copy wbkName.Sheets("CopyMacro").Range("E14")