复制工作表时下标超出范围

时间:2015-04-01 07:38:20

标签: vba excel-vba excel

我想创建一个命令按钮,将所选文件导入当前工作簿 我得到了Subscript out of range error,我找不到解决办法 这就是我所拥有的:

Private Sub CmdBrowseFile_Click()
Dim intChoice, total As Integer
Dim file, ControlFile As String

ControlFile = ActiveWorkbook.Name
'only allow the user to select one file
Application.FileDialog(msoFileDialogOpen).AllowMultiSelect = False
'Remove all other filters
Call Application.FileDialog(msoFileDialogOpen).Filters.Clear
'Add a custom filter
Call Application.FileDialog(msoFileDialogOpen).Filters.Add( _
    "Text Files Only", "*.xlsx")
'make the file dialog visible to the user
intChoice = Application.FileDialog(msoFileDialogOpen).Show
'determine what choice the user made
If intChoice <> 0 Then
    'get the file path selected by the user
    file = Application.FileDialog( _
        msoFileDialogOpen).SelectedItems(1)
    'open file
    Workbooks.Open fileName:=file
    total = Workbooks(ControlFile).Worksheets.Count
    Workbooks(file).Worksheets(ActiveSheet.Name).Copy _
    after:=Workbooks(ControlFile).Worksheets(total)
    Windows(file).Activate
    ActiveWorkbook.Close SaveChanges:=False
    Windows(ControlFile).Activate
End If

1 个答案:

答案 0 :(得分:1)

错误:

线路上发生错误
Workbooks(file).Worksheets(ActiveSheet.Name).Copy...因为Workbooks(<argument>)只期待文件名,没有完整路径。您正在解析完整路径。

固定代码

Private Sub CmdBrowseFile_Click()

    Dim intChoice As Integer, total As Integer 'note the correct declaring, for each variable As Type
    Dim strFilePath As String, strControlFile As String
    Dim strFileName As String

    strControlFile = ActiveWorkbook.Name
    'only allow the user to select one strFilePath
    Application.FileDialog(msoFileDialogOpen).AllowMultiSelect = False
    'Remove all other filters
    Call Application.FileDialog(msoFileDialogOpen).Filters.Clear
    'Add a custom filter
    Call Application.FileDialog(msoFileDialogOpen).Filters.Add( _
        "Text Files Only", "*.xlsx")
    'make the strFilePath dialog visible to the user
    intChoice = Application.FileDialog(msoFileDialogOpen).Show
    'determine what choice the user made
    If intChoice <> 0 Then
        'get the strFilePath path selected by the user
        strFilePath = Application.FileDialog( _
            msoFileDialogOpen).SelectedItems(1)
        'get the file name
        strFileName = Dir(strFilePath)
        'open strFilePath
        Workbooks.Open fileName:=strFilePath
        total = Workbooks(strControlFile).Worksheets.Count
        Workbooks(strFileName).Worksheets(ActiveSheet.Name).Copy _
        after:=Workbooks(strControlFile).Worksheets(total)
        Windows(strFileName).Activate
        ActiveWorkbook.Close SaveChanges:=False
        Windows(strControlFile).Activate
    End If

End Sub  

备注

主要更改是Dim strFileName As StringstrFileName = Dir(strFilePath)以及打开新书后代码中的用法。为了测试目的,我更改了变量名称,我可以通过这种方式更容易地阅读它。您可以使用重命名工具还原更改。