2017-04-22 42 views
-1

我想将数据从一个工作簿复制到另一个工作簿。但是当我通过一个宏快捷键(Ctrl + Shift + O)运行它时,它不起作用。程序在调试模式下工作,但不通过快捷方式运行时

但是,当我在调试模式下运行我的程序时,它正常工作。我不明白为什么。

下面是代码:

Option Explicit 

Sub CONSUMED() 
    Dim wp As Workbook, wc As Worksheet 
    Dim UVAL As Variant, erow As Integer, lastrow As Integer, E As Integer 

    UVAL = InputBox("Enter a code:") `user will enter the value, which user wants to shift.` 
    Set wc = ThisWorkbook.Sheets("consumption") 
    erow = wc.Cells(wc.Rows.Count, 4).End(xlUp).Row   
    Set wp = Workbooks.Open("F:\report\Book1.xlsm") ' where dtat will move' 

    For E = erow To 7 Step -1 
     If Cells(E, 11) = UVAL Then ' when uservalue(uval) meets data from sheet' 
      Application.CutCopyMode = True 
      wc.Range(wc.Cells(E, 2), wc.Cells(E, 12)).Copy 
      With wp.Sheets("Sheet1") 
       lastrow = .Range("B" & .Rows.Count).End(xlUp).Row + 1 
       .Range(.Cells(lastrow, 1), .Cells(lastrow, 12)).PasteSpecial xlPasteValues 
       wc.Range(wc.Cells(E, 2), wc.Cells(E, "XFD")).Delete 
      End With 
      E = E - 1 
     End If 
    Next 
    wp.Save 
    wp.Close True 
    Application.CutCopyMode = False 
End Sub 
+1

那不是VB.NET代码。删除标签并阅读[问]并采取[旅游]'不完全运行'是一个可怕的问题描述。 – Plutonix

+0

当您打开工作簿时,ActiveSheet会更改。您的For/Next循环顶部的If语句需要被限定在适当的工作表中。 –

回答

1
Option Explicit 
Sub CONSUMED() 
Dim wp As Workbook, wc As Worksheet 
Dim UVAL As Variant, erow As Integer, lastrow As Integer, E As Integer 

UVAL = InputBox("Enter a code:") 'user will enter the value, which user wants to shift. 
Set wc = ThisWorkbook.Sheets("consumption") 
erow = wc.Cells(wc.Rows.Count, 4).End(xlUp).Row 

Set wp = Workbooks.Open("B:\Book1.xlsm") ' where dtat will move' 
'Add this line make source workbook active 
wc.Activate 


For E = erow To 7 Step -1 
'Convert Cell value to string InputBox returns string value 
If CStr(Cells(E, 11).Value) = UVAL Then ' when uservalue(uval) meets data from sheet' 


Application.CutCopyMode = True 

wc.Range(wc.Cells(E, 2), wc.Cells(E, 12)).Copy 

    With wp.Sheets("Sheet1") 
lastrow = .Range("B" & .Rows.Count).End(xlUp).Row + 1 

.Range(.Cells(lastrow, 1), .Cells(lastrow, 12)).PasteSpecial xlPasteValues 
wc.Range(wc.Cells(E, 2), wc.Cells(E, "XFD")).Delete 
    End With 
E = E - 1 
End If 
Next 
wp.Save 
wp.Close True 
Application.CutCopyMode = False 

End Sub 
+0

根据您的建议进行了必要的更改。但它不起作用。当我运行程序时,只需打开另一个工作簿,然后停止工作。 @Wojciech Wojtulewski – DV47

相关问题