我已将工作簿分配给变量。 然后我正在做一些事情并保存文件并关闭工作簿:
如果我想在循环中使用此代码,那么设置工作簿是不是一个好主意?
For i = 1 To UBound(a_ven_lst1)
Set wb_input1 = Application.Workbooks.Add
Set ws_input1 = wb_input1.Sheets(1)
.Rows(1).Copy ws_input1.Rows(1)
.Rows(d_fst_ven_row & ":" & d_lst_ven_row).Copy ws_input1.Rows(2)
s_save_path = f_str_file_name(ws_input1.Cells(2, i_ven_col_cnt).Value)
s_file_path = s_path & "\" & s_save_path & ".xlsx"
a_ven_lst1(i, 2) = s_file_path
wb_input1.SaveAs Filename:=s_file_path
wb_input1.Close True
Set wb_input1 = Nothing
Next i
我是否以适当的方式杀死了这个变量? 在破坏代码之后,我看到VBA编辑器中仍然存在一些对象,但远远超出了这一点。
答案 0 :(得分:3)
替代代码,不用担心工作簿变量设置和取消设置
With ws_input
'...
Dim rowToCopy1 As Range, rowToCopy2 As Range
Set rowToCopy1 = .Rows(1) '<--| set first row to copy, since it's "constant" against the subsequent loop
Set rowToCopy2 = .Rows(d_fst_ven_row & ":" & d_lst_ven_row) '<--| set second row to copy, since it's "constant" against the subsequent loop
For i = 1 To UBound(a_ven_lst1)
With Application.Workbooks.Add '<--| open a new workbook and reference its instance
With .Sheets(1) '<--| reference referenced workbook sheet(1)
rowToCopy1.Copy .Rows(1)
rowToCopy1.Copy .Rows(2)
s_save_path = f_str_file_name(.Cells(2, i_ven_col_cnt).Value)
End With
s_file_path = s_path & "\" & s_save_path & ".xlsx"
a_ven_lst1(i, 2) = s_file_path
.SaveAs Filename:=s_file_path
.Close True
End With '<--| discard the instance of the opened workbok
Next i
'...
End With