我正在研究VBA中的模块:
当我运行模块时,我收到错误
'下标超出范围'
因此对话框打开,我可以选择一个文件,打开它,但是当复制/粘贴数据时,它会失败。
以下是代码:
Sub Import()
Dim WS As Worksheet
Dim fd As Office.FileDialog
Dim Wb As Workbook
Dim txtFilePath As String
Dim txtFileName As String
Dim fso As New FileSystemObject
Set fd = Application.FileDialog(msoFileDialogFilePicker)
Application.ScreenUpdating = False
Application.DisplayAlerts = False
With fd
.AllowMultiSelect = False
'Title of dialog box.
.Title = "Select a file"
If .Show = True Then
txtFilePath = .SelectedItems(1)
End If
End With
txtFileName = fso.GetFileName(txtFilePath)
Workbooks.Open Filename:=txtFilePath
'The workbook, the data is pasted to, is called "Rapport_auto"
Workbooks(txtFileName).Worksheets("Rapport").Copy _
after:=Workbooks("Rapport_auto").Worksheets(1)
'Change name of active sheet
ActiveSheet.Name = "Data"
'Close imported workbook
Workbooks(txtFileName).Close
End Sub
对于我做错了什么有任何建议吗?
// UPDATE //在调试过程中我修复了问题 - 请参阅下面的回复。
答案 0 :(得分:0)
对于我做错了什么有任何建议吗?
未打开第二个工作簿(Rapport_auto)
。
Copying a worksheet to another workbook using VBA
答案 1 :(得分:0)
@Vityata,'Rapport_auto'文件是我运行代码的文件,因此它应该是打开的。
然而,我刚刚解决了这个问题 - 我不知道为什么它工作得更好,但解决方案是将代码更改为:
Dim currentFileName As String
currentFileName = ActiveWorkbook.Name
Set Wb = Workbooks(currentFileName)
Workbooks(txtFileName).Worksheets("Rapport").Copy _
after:=Wb.Worksheets(1)
而不仅仅是
Workbooks(txtFileName).Worksheets("Rapport").Copy _
after:=Workbooks("Rapport_auto").Worksheets(1)
我正在分割代码以尝试调试较小的位,但最终它只是工作:)