在从其他工作簿创建工作表时很难使用VBA

时间:2017-05-26 06:47:38

标签: excel vba excel-vba

我在VBA中编写了这种代码:

Sub itemselecter()

Dim Filename1 As String
Dim Sourcewb1 As Workbook
Dim Targetwb1 As Workbook

With Application.FileDialog(msoFileDialogFilePicker)
  .AllowMultiSelect = False

If .Show = 0 Then
    Exit Sub
  Else
    Filename1 = .SelectedItems(1)
    Err.Clear
    On Error GoTo 0
  End If
End With

Application.ScreenUpdating = False

Set Sourcewb1 = Workbooks.Open(Filename1)         'Open FIC data
Set Targetwb1 = ThisWorkbook

Targetwb1.Worksheets("Data").ClearContents
Sourcewb1.Worksheets(1).Cells.Copy Destination:=Targetwb.Sheets("Data").Cells
Sourcewb1.Close (False)

Application.ScreenUpdating = True

End Sub

当我尝试从文档中选择文件时,它在错误424时给了我。有什么问题?

2 个答案:

答案 0 :(得分:0)

请更改此行代码,

Targetwb1.Worksheets("Data").ClearContents



这样的东西
Targetwb1.Sheets("Data").Cells.ClearContents

请让我建议您检查该工作簿中是否存在“数据”表。

答案 1 :(得分:0)

尝试下面的代码,检查我修改过的代码中的注释。

如果您在代码顶部添加了Option Explicit,则不会发生第二个错误(将TargetwbTargetwb1混为一谈)。

<强>代码

Option Explicit

Sub itemselecter()

Dim Filename1 As String
Dim Sourcewb1 As Workbook
Dim Targetwb1 As Workbook

With Application.FileDialog(msoFileDialogFilePicker)
    .AllowMultiSelect = False

    If .Show = 0 Then
        Exit Sub
    Else
        Filename1 = .SelectedItems(1)
        Err.Clear
        On Error GoTo 0
    End If
End With

Application.ScreenUpdating = False

Set Sourcewb1 = Workbooks.Open(Filename1)         'Open FIC data
Set Targetwb1 = ThisWorkbook

Targetwb1.Worksheets("Data").Cells.ClearContents '<-- added .Cells to clear the worksheet's entire cells contents
Sourcewb1.Worksheets(1).Cells.Copy Destination:=Targetwb1.Sheets("Data").Cells  '<-- need to be Targetwb1 not Targetwb
Sourcewb1.Close (False)

Application.ScreenUpdating = True

End Sub