VBA:粘贴停止工作(突然)在特定的macros

我是一个非常新的,自学成才的程序员,所以请记住你的回应。 我已经广泛search这个和其他论坛,似乎无法find类似的问题。

下面的代码已经工作了几个星期,并没有改变。 (我的macros包含了更多的variables和代码,但是我知道这些碎片是可以工作的,所以为了清楚起见,我把它们留了下来)。 从我可以告诉PasteSpecialfunction是特别不起作用。

Dim StimSheet As String ActiveCell.Rows("1:290").EntireRow.Select Selection.Copy 'Copies the data for the current stimulus StimSheet = Application.InputBox("Enter the name of the stimulus") 'asks name of the stimulus Sheets.Add After:=Worksheets(Worksheets.Count) ActiveSheet.Name = StimSheet 'adds new sheet at the end and names whatever you input as stimulus name Sheets(StimSheet).Select Selection.PasteSpecial Paste:=xlPasteValues 'pastes data into new sheet 

在这一点上没有错误,macros复制并创build新的工作表后,简单地停止。

这是我所知道的/曾经尝试的:

  1. macros已成功创build并命名新工作表并将select复制到剪贴板,因为我可以在运行macros后手动粘贴它。 它似乎被卡在粘贴片。

  2. 其他使用完全相同的复制/粘贴格式的macros仍然正常工作

  3. 另一个类似程序的论坛build议在即时窗口中input“Application.EnableEvents = True”。 这并没有改变任何东西。

  4. 这个macros已经工作了几个星期没有错误。 我已经使用以前保存的代码来创build新的macros,以防当前某个东西被无意中改变了,但是这也不起作用。

  5. 粘贴选项在一个新文件上工作一次,然后停止再次工作。

预先感谢您的build议。

您可能会发现问题在于您无法控制此代码适用于哪个工作簿和工作表。 尽可能避免ActiveSheetSelectSheet没有父母。

如果您只需要复制单元格的值而不进行任何格式化,则不需要“ Paste ”。

尝试改变你的代码到下面,看看你是否有更好的运气:

 Const BOOK_NAME As String = "Book1.xlsm" 'change this to your workbook name Const SOURCE_SHEET_NAME As String = "Sheet1" 'change this to your sheet name Dim wb As Workbook Dim sourceSheet As Worksheet Dim newSheet As Worksheet Dim newSheetName As String Dim validName As Boolean Dim rng As Range ' Set the book, sheet and range objects Set wb = Workbooks(BOOK_NAME) Set sourceSheet = wb.Worksheets(SOURCE_SHEET_NAME) Set newSheet = wb.Worksheets.Add(After:=wb.Worksheets(wb.Worksheets.Count)) ' Acquire the new sheet name and check it's valid. Do newSheetName = InputBox("Enter the name of the stimulus") On Error Resume Next newSheet.Name = newSheetName validName = (Err.Number = 0) On Error GoTo 0 If Not validName Then MsgBox "Sheet name isn't valid. Try again." Loop Until validName ' Write the values into the new sheet Set rng = sourceSheet.Cells(1, 1).Resize(290, sourceSheet.UsedRange.Columns.Count) newSheet.Range(rng.Address).value = rng.Value2 

我搬了这条线:

 StimSheet = Application.InputBox("Enter the name of the stimulus") 

到方法的顶部,它似乎可靠地工作。 我希望我可以告诉你为什么,但至less你可以继续。 也许这与改变焦点有关。

另外,当它失败了(Office 2013)我得到了以下错误:

运行时错误1004:应用程序定义或对象定义的错误。

当Sub在一个表单代码后面,这个:

Range类的运行时错误“1004”PasteSpecial方法失败。

当粘贴在一个模块。