我想要创建一个命令按钮,它将选定的文件导入当前工作簿。
我得到了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发布于 2015-04-01 08:39:47
错误:
错误发生在行上。
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 String和strFileName = Dir(strFilePath),以及它在打开新书后在代码中的用法。为了测试目的,我更改了变量名,这样可以更容易地读取它。您可以使用重命名工具来还原更改。
https://stackoverflow.com/questions/29385312
复制相似问题