程序在调试模式下工作,但在通过快捷方式运行时不工作

时间:2017-04-22 17:55:45

标签: vba excel-vba excel

我想将数据从一个工作簿复制到另一个工作簿。但是当我通过宏快捷键(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 个答案:

答案 0 :(得分: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