当我复制macros中的单元格时,Excel崩溃
我有一个简单的macros,打开一个CSV文件,应该复制工作的工作簿中的单元格:
Sub macro1() Dim build_w As Workbook Dim build_s As Worksheet Dim folder_st As String Application.ScreenUpdating = False folder_st = "c:\file.csv" Set build_w = Application.Workbooks.Open(folder_st) Set build_s = build_w.Sheets("build") build_s.Range("A1").Copy ActiveSheet.Paste Range("A284") build_w.Close True Application.ScreenUpdating = True End Sub
如果我注释掉build_s.Range(“A1”)这行,复制一切都很好,但是如果我把它放在这里,Excel每次都会崩溃。
有什么build议么?
你知道你粘贴时的ActiveSheet
本身就是build_s
工作表吗? 使用Activesheet
等Activesheet
时,这是个问题。 总是最好精确指定工作表和工作簿对象,而不必指定给定时刻处于活动状态的对象。
最终,为了得到你想要的行为,你应该这样做:
build_s.Range("A1").Copy ThisWorkbook.ActiveSheet.Range("A284")
您是否尝试过处理任何可能的错误:
On Error GoTo MyHandler MyHandler:
PFB为需要的代码。 CSV文件不能有多张纸,所以这就是为什么它一定会崩溃。 CSV文件只能有一个表格,所以不需要指定表格名称。
Sub macro1() 'Declared variables Dim build_w As Workbook Dim folder_st As String 'Disabling screen updates Application.ScreenUpdating = False 'Initializing the file name folder_st = "c:\file.csv" 'Opening the workbook Set build_w = Workbooks.Open(folder_st) 'Copying the value of cell A1 Range("A1").Copy 'Selecting the cell A284 Range("A284").Select 'Pasting the copied value ActiveSheet.Paste 'Saving the workbook by saving the .CSV file build_w.Close True 'Enabling screen updates Application.ScreenUpdating = True End Sub
这是因为在打开csv文件时,它将成为活动工作簿及其唯一工作表“ 活动”工作表
你可以利用这个优势如下:
Option Explicit Sub macro1() Dim folder_st As String Application.ScreenUpdating = False folder_st = "c:\file.csv" With ActiveSheet '<--| reference your currently active sheet before opening csv file Application.Workbooks.Open(folder_st).Sheets("build").Range("A1").Copy '<--| open csv file (and it becomes the Active Workbook) and reference its "build" sheet range "A1" and copy it... .Range("A284").PasteSpecial '<--| paste it to your referenced sheet range A284 Application.CutCopyMode = False '<--| release clipboard ActiveWorkbook.Close False '<--| close Active workbook, ie the csv file End With Application.ScreenUpdating = True End Sub