Workbook.Open后宏停止

时间:2018-03-29 00:35:17

标签: excel vba excel-vba

我正在尝试复制打开工作簿,复制范围并将其粘贴到另一个工作簿中。打开工作簿并选择范围后,宏停止。

如果我稍后在代码中使用Workbook.close,则宏会在同一点停止,但工作簿甚至都没有打开。

在使用Workbook.Open时,我在其他线程中看到了“shift键”问题,但事实并非如此。

Sub importSpecialist()


Dim ws As Worksheet
Set ws = Worksheets("myworksheet")

Dim lws As Integer
lws = ws.Range("B3").End(xlDown).Row

Dim savePath As String
Dim saveName As String
Dim saveMonth As String
Dim fileExtension As String
Dim fullPath As String
Dim version As Integer

Dim FSO
Set FSO = CreateObject("Scripting.FileSystemObject")

savePath = "C:\mypath\"
saveName = "myname_"
saveMonth = Format(Date, "mm")
fileExtension = ".xlsx"
fullPath = savePath & saveName & saveMonth & fileExtension

Debug.Print fullPath

If FSO.fileexists(fullPath) Then
    Dim i As Integer
    Dim wb1 As Workbook
    Set wb1 = Workbooks.Open(fullPath)
    wb1.Sheets(1).Range("C4:C18").Copy
        For i = 1 To lws
            On Error Resume Next
            If ws.Range("B" & (i + 2)) = Format(Date, "mm/yyyy") Then
                ws.Cells(Range("N" & (i + 2))).PasteSpecial
            End If
        Next
End If
End Sub

1 个答案:

答案 0 :(得分:0)

尝试像这样打开它:

Dim xl As New Excel.Application
    Application.DisplayStatusBar = False
    Application.DisplayAlerts = False
    xl.Workbooks.Open (Worksheets("MAIN").Range("B7").Value)//your path
    xl.Visible = False //or true
   //your code here
    xl.Quit
    Set xl = Nothing

''如果您要从中选择范围,请使用xl.Worksheets()。Range()。选择