VBA-提示用户打开工作簿并选择工作表,打开空白文件

问题描述 投票:0回答:1

我希望用户选择一个工作簿,然后选择他们需要的工作表。该代码在Debug-Step Into时可以完美工作。但是,当通过按钮运行完整宏时,文件确实会打开并提示您选择工作表,但看不到工作表或单元格。全部都是空白。没有文件保护。列名和行号不可见


 Sub LoadData()
     Dim ws As Worksheet
     Dim desiredSheetName As String
     Dim c As String

     Application.ScreenUpdating = False
     Application.DisplayAlerts = False

     ans = MsgBox("Choose the file to retrive the data?", vbYesNo, "Choose Source")
     If ans = vbYes Then
        myfile = Application.GetOpenFilename(, , "Browse for Workbook")
        If myfile <> False Then
           ThisWorkbook.Sheets("Destination").Range("AA2") = myfile
           Set src_data = Workbooks.Open(myfile)

          On Error Resume Next
          desiredSheetName = InputBox("Select any cell inside the target sheet: ",type:=8).worksheet.name 
          sht = desiredSheetName
          On Error GoTo 0

          Set dest = ThisWorkbook.Worksheets("Destination")

          src_data.Activate

          lastcell = src_data.Sheets(sht).Cells(Rows.Count, "C").End(xlUp).Row
          LastRowD = dest.Cells(dest.Rows.Count, "F").End(xlUp).Offset(0).Row

          src_data.Activate
          Sheets(sht).Select
          Range("A:B,D:D").Select
          Selection.Copy
          dest.Activate
          Range("F1").Select
          Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, skipblanks:=False, Transpose:=False

          src_data.Close False

          dest.Select

        End If
   Else
     Exit Sub
 End If

Application.DisplayAlerts = True
Application.ScreenUpdating = True

结束子


excel vba worksheet
1个回答
0
投票

相应地限定对象(图纸和范围),以确保每一行都引用正确的图纸或书籍。您的代码一直运行而看不到任何可见的原因是因为您关闭了屏幕更新。

此外,在切换屏幕更新之前,代码中有一个Exit Sub。因此,当myfile = False结束时,关闭了屏幕更新,退出了子菜单。您可以允许代码从头到尾运行,而无需使用提前退出(如下面的示例所示),也可以只在Exit Sub

之前将屏幕更新重新打开。
Application.ScreenUpdating = False

ans = MsgBox("Choose the file to retrive the data?", vbYesNo, "Choose Source")

If ans = vbYes Then
    myfile = Application.GetOpenFilename(, , "Browse for Workbook")

    If myfile <> False Then

        ThisWorkbook.Sheets("Destination").Range("AA2") = myfile
        Set src_data = Workbooks.Open(myfile)

        On Error Resume Next
            desiredSheetName = InputBox("Select any cell inside the target sheet: ", Type:=8).Worksheet.Name
            sht = desiredSheetName
        On Error GoTo 0

        Set dest = ThisWorkbook.Worksheets("Destination")
        lastcell = src_data.Sheets(sht).Cells(Rows.Count, "C").End(xlUp).Row
        LastRowD = dest.Cells(dest.Rows.Count, "F").End(xlUp).Offset(0).Row

        src_data.Sheets(sht).Range("A:B,D:D").Copy
        dest.Range("F1").PasteSpecial xlPasteValues

        src_data.Close False
        dest.Select
    End If
End If

Application.ScreenUpdating = True
© www.soinside.com 2019 - 2024. All rights reserved.