【问题标题】:Excel 2013 - Macro shortcuts do not work properly, but the macro works fine by active it manuallyExcel 2013 - 宏快捷方式无法正常工作,但手动激活宏可以正常工作
【发布时间】:2016-10-26 21:49:35
【问题描述】:

我有一个 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

【问题讨论】:

    标签: vba excel


    【解决方案1】:

    执行以下操作:

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-08-24
      • 2014-07-08
      • 1970-01-01
      • 2012-12-19
      • 2016-01-07
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多