Excel 2013 - 宏快捷方式无法正常工作,但通过手动激活宏可以正常工作

时间:2016-06-24 09:57:27

标签: excel vba excel-vba

我有一个VBA脚本可以将数据从当前文件复制到另一个工作簿。如果我手动运行它,代码运行良好。它从当前工作簿复制数据,然后打开另一个,粘贴数据并最终关闭它。

但是,如果我通过快捷方式运行此宏,它只会粘贴数据而不会关闭目标工作簿。

Sub CopyToBMD()
'
' CopyToBMD Macro
' Copy Lastest BMD price to appropriate day in the table
'
'
Dim target As Integer
Dim LDate As String

Sheets(1).Select
Range("B48:R48").Copy

LDate = Date

If Cells(40, 2).Value = Cells(1, 2).Value Then
    target = 2
Else
    target = 8
End If

' Paste data to BMD&CBOT
Dim wbk As Workbook
Dim folderPath As String
Dim ws As Worksheet

'Find file location
folderPath = Application.ActiveWorkbook.Path
FilePath = Dir(folderPath & "\BMD&CBOT.xlsx")

Set wbk = Workbooks.Open(folderPath & "\" & FilePath)
Set ws = wbk.Sheets("CPO-Jun 16")

' i is the row number
Dim i As Integer

For i = 4 To 34
    If Cells(i, 1).Value = LDate Then
        ws.Cells(i, target).Select
        Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
        :=False, Transpose:=False
    End If
Next i

wbk.Close True

End Sub

1 个答案:

答案 0 :(得分:0)

执行以下操作:

[your code]
    End If
Next i
debug.print wbk.name
wbk.Close True

End Sub

它打印什么?简而言之 - 不要像使用wbk那样使用“ActiveWorkbook”,而是明确地引用它。