我有一个简单的宏打开一个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每次都会崩溃。
有什么建议吗?
答案 0 :(得分:2)
您是否知道粘贴时ActiveSheet
本身就是build_s
工作表?使用像Activesheet
这样的东西时,这就是问题所在。最好精确地指定工作表和工作簿对象,而不必指望在给定时刻处于活动状态的内容。
最终,为了获得你想要的行为,你应该这样做:
build_s.Range("A1").Copy ThisWorkbook.ActiveSheet.Range("A284")
答案 1 :(得分:0)
您是否尝试使用以下方法处理任何可能的错误:
On Error GoTo MyHandler
MyHandler:
答案 2 :(得分:0)
它是因为在打开csv文件后它变为 Active 工作簿,而它唯一的工作表是 Active 工作表
你可以利用这个优势,如下所示:
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, i.e. the csv file
End With
Application.ScreenUpdating = True
End Sub
答案 3 :(得分:0)
需要代码的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