我有一个宏从BD工作表中复制一些列并粘贴到另一个工作表中。
我已经在Excel 2007中使用了此代码,但是在选择工作表时遇到了问题,然后在Excel 2010及更高版本中复制/粘贴。似乎问题不在我的.Select
中。它似乎在PasteSpecial()
中自动选择with Sheet()
并执行其他.copy()
而不返回到前一页(屏幕每次闪烁pasteSpecial
) - 我不知道我知道我是否足够清楚。 [有时它工作正常,尤其是使用调试器]
代码
Const BD_SHEET As String = "Estrategia"
Const PRICE_SHEET As String = "Precos"
Public Sub Execute()
....
actualCalculate = Application.Calculation
Application.Calculation = xlCalculationManual
LoadPrices()
Application.Calculate
Application.Calculation = actualCalculate
End Sub
Private Sub LoadPrices()
Dim lastSheet As Worksheet
Set lastSheet = ActiveSheet
Sheets(BD_SHEET).Select
lastRow = [A1000000].End(xlUp).row
With Sheets(PRICE_SHEET)
Range(Cells(2, 2), Cells(lastRow, 2)).Copy
.[A2].PasteSpecial xlPasteValues '<---- Working
Range(Cells(2, 7), Cells(lastRow, 7)).Copy
.[B2].PasteSpecial xlPasteValues '<---- Working
Range(Cells(2, 9), Cells(lastRow, 10)).Copy '<---- Error!
.[C2].PasteSpecial xlPasteValues
Range(Cells(2, 12), Cells(lastRow, 12)).Copy '<---- Error!
.[E2].PasteSpecial xlPasteValues
End With
lastSheet.Select
End Sub
我可以删除.Select
并添加Set theSheet = Sheets(BD_SHEET)
,但代码将是durty。
例:
...
Set lastSheet = ActiveSheet
Set bdSheet = Sheets(BD_SHEET)
lastRow = [A1000000].End(xlUp).row
With Sheets(PRICE_SHEET)
bdSheet.Range(bdSheet.Cells(2, 2), bdSheet.Cells(lastRow, 2)).Copy
.[A2].PasteSpecial xlPasteValues
End With
...
答案 0 :(得分:2)
but the code is going to be durty.
那是因为你的做法是错误的
而不是
With Sheets(PRICE_SHEET)
bdSheet.Range(bdSheet.Cells(2, 2), bdSheet.Cells(lastRow, 2)).Copy
.[A2].PasteSpecial xlPasteValues
End With
这样做
With bdSheet
.Range(.Cells(2, 2), .Cells(lastRow, 2)).Copy
Sheets(PRICE_SHEET).[A2].PasteSpecial xlPasteValues '<---- Working
End With
也永远不要使用硬编码值来查找最后一行。您可能会看到有关如何计算最后一行的This。
另外
Range1.Copy
Range2.PasteSpecial xlPasteValues
可以写成
Range2.Value = Range1.Value
应用上述内容,我重新编写了代码。这是你在尝试什么? (的未测试强>)
Private Sub LoadPrices()
Dim wsCopyFrm As Worksheet, wsCopyTo As Worksheet
Dim rng As Range
Dim lastRow As Long
Set wsCopyFrm = ThisWorkbook.Sheets(BD_SHEET)
Set wsCopyTo = ThisWorkbook.Sheets(PRICE_SHEET)
With wsCopyFrm
lastRow = .Range("A" & .Rows.Count).End(xlUp).Row
Set rng = .Range(.Cells(2, 2), .Cells(lastRow, 2))
wsCopyTo.Range("A2").Resize(rng.Rows.Count, rng.Columns.Count).Value = rng.Value
Set rng = .Range(.Cells(2, 7), .Cells(lastRow, 7))
wsCopyTo.Range("B2").Resize(rng.Rows.Count, rng.Columns.Count).Value = rng.Value
Set rng = .Range(.Cells(2, 9), .Cells(lastRow, 10))
wsCopyTo.Range("C2").Resize(rng.Rows.Count, rng.Columns.Count).Value = rng.Value
Set rng = .Range(.Cells(2, 12), .Cells(lastRow, 12))
wsCopyTo.Range("E2").Resize(rng.Rows.Count, rng.Columns.Count).Value = rng.Value
End With
End Sub