【发布时间】:2015-06-11 00:51:13
【问题描述】:
我正在编写一个宏以在 Excel 工作表中工作,该工作表保存在模板中,然后从单独的应用程序导出为 .xls 或 .xlsx。此宏用于根据输入到单元格中的数量复制两列“x”次。
Sub Matrix_Quantity()
Dim x As Integer
x = ActiveWorkbook.Sheets("Inspection Sampling Matrix").Cells(11, 4)
Dim n As Integer
n = x - 1
For numtimes = 1 To n
'Loop by using x as the index number to make x number copies.
Sheets("Inspection Report").Columns("F:G").Select
Selection.Copy
Selection.Insert Shift:=x1 + nToRight
Next
End Sub
我遇到的问题是,当使用模板 (.xlt) 运行宏时,它运行良好。一旦模板转换为 .xls 或 .xlsx,它就会发现工作并给出运行时错误。调试宏时它会突出显示
Sheets("Inspection Report").Columns("F:G").Select
我的感觉是它正在寻找 .xlt 工作簿中的列,但是当转换为 .xls 或 .xlsx 时,它仍在尝试寻找 .xlt 工作簿,我不确定它是如何或为什么这样做的这个。
【问题讨论】:
-
这是因为您的工作表
Inspection Report在宏运行时未处于活动状态。请阅读how to avoid using Select/Active statements。你可以用Sheets("Inspection Report").Columns("F:G").Copy和Sheets("Inspection Report").Columns("F:G").Insert Shift:=x1 + nToRight替换你的代码 -
感谢您的回复。当我插入您推荐的代码并运行宏时,Excel 将崩溃且没有错误。它只是提出了 Windows 错误“Microsoft Excel 已停止工作”
-
其实,我不明白你在这里做什么:
Shift:=x1 + nToRight?应该是Shift:=xlToRight?