【发布时间】:2020-11-26 00:54:28
【问题描述】:
我有一个文件夹,用于存储两种类型的工作簿,它们是 [person_name]-RESUME.xlsx 和
[person_name].xlsx。使用我的代码,用户可以同时选择这两个文件。
我希望单击工作簿上的按钮,选择这两个文件,将 [person_name]-RESUME.xlsx 中的内容复制到 sheet1,将 [person_name].xlsx 中的内容复制到 sheet2,然后关闭这两个文件。
使用我的代码时出现错误Run-time error '91': Object variable or With block variable not set,当我单击“调试”时,它会在我的函数中突出显示ElseIf,我已经尝试打开单个文件的函数代码,它工作正常。下面是我的代码。
Sub opening_multiple_file()
Dim i As Integer
Dim myrange As Range
Dim n_rows_A As Long, n_rows_B As Long, n_rows As Long
'Opening File dialog box
With Application.FileDialog(msoFileDialogFilePicker)
'Enabling multiple files select
.AllowMultiSelect = True
.Filters.Clear
'Only Excel files can be selected
.Filters.Add "Excel Files", "*.xls*"
If .Show = True Then
For i = 1 To .SelectedItems.Count
'Opening selected file
Workbooks.Open .SelectedItems(i)
'Check if file is a resume
If InStr(.SelectedItems(i), "-RESUME") Then
n_rows_A = CountRows(myrange)
n_rows_B = CountRows(myrange.Offset(0, 1))
n_rows = WorksheetFunction.Max(n_rows_A, n_rows_B)
' Do the copy here
Sheets("Sheet1").Range("A1").Resize(n_rows, 12).Value = _
myrange.Resize(n_rows, 12).Value
Else
n_rows_A = CountRows(myrange)
n_rows_B = CountRows(myrange.Offset(0, 1))
n_rows = WorksheetFunction.Max(n_rows_A, n_rows_B)
' Do the copy here
Sheets("Sheet2").Range("A1").Resize(n_rows, 12).Value = _
myrange.Resize(n_rows, 12).Value
End If
Next i
End If
End With
End Sub
Function CountRows(ByRef r As Range) As Long
If IsEmpty(r) Then
CountRows = 0
ElseIf IsEmpty(r.Offset(1, 0)) Then
CountRows = 1
Else
CountRows = r.Worksheet.Range(r, r.End(xlDown)).Rows.Count
End If
End Function
我还想关闭新打开的工作簿。
【问题讨论】:
-
如何识别新打开的工作簿中的工作表?你知道他们的名字,他们的索引吗?您确定正确的将始终处于活动状态(已选中)吗?请务必澄清。发生错误是因为
myrange始终为Nothing。你忘了在Workbooks.Open .SelectedItems(i)之后使用Set myrange = Activesheet.Columns("A")之类的东西。 -
新打开的工作簿始终具有相同的布局和一个名为“Sheet1”的工作表。我已经添加了那行代码,现在我得到了
Run-time error '1004': Application-defined or object-defined error