2014-05-09 3 views
0

.csv 보고서 파일에서 일부 데이터를 가져 오려고합니다. 이 클래스의 SetBook에 오류가 있으며 xls 또는 xlsx 파일에서만 작동합니다.CSV 파일의 데이터를 Excel로 가져 오기

경로는 셀의 사용자에 의해 정의되며 C : \ Folder \와 같은 형식이며 코드의 나머지 부분은 파일의 이름을 지정합니다. 이는 매일 바뀌고 있습니다.

Sub PullData() 
Application.ScreenUpdating = False 

Dim PathFile As String 
    PathFile = Cells(23, 15) 

Dim ClassBook As Workbook 
    Set ClassBook = PathFile & "class" & Format(Now() + 1, "ddmmyy") & "-booked.csv" 

Dim Template As Workbook 
    Set Template = ActiveSheet 

    Sheets(Template).Cells(5, 15) = Sheets(ClassBook).Cells(2, 1) 

Application.ScreenUpdating = True 
End Sub 

미리 도움 주셔서 감사합니다!

+0

이 파일은 열려있는 파일이나 파일입니까? –

답변

0

당신이 이미 존재하는 파일을 열려고 시도 할 경우, 사용 : Dim입니다 템플릿 (할당하는 것처럼

Dim ClassBook As Workbook, ClassSheet As Worksheet 
Set ClassBook = Workbooks.Open(PathFile & "class" & Format(Now() + 1, "ddmmyy") & "-booked.csv") 
Set ClassSheet = ClassBook.ActiveSheet 

또한, 더 아래 코드에서, 그것은 보이는 'A Workbook에 관한 거라고 . WorkSheet입니다 ActiveSheet, 대신 이것을 사용하는 것이 좋습니다 :

Dim Template As Worksheet 
Set Template = ThisWorkbook.Worksheets("SomeSheetName") '<~ put the name of the sheet you want to use as a template here 

그런 다음, 아래로 우리의 방식으로 작동합니다, 당신은 쓸 수 있습니다 :

Template.Cells(5, 15) = ClassSheet.Cells(2, 1) 

마지막으로, 사용자가 불가피하게 뭔가 당신이 기대하지 않았다 않을 때 선 아래로 몇 가지 디버깅을 절약 할 수있는, 당신의 PathFile 할당에 더 명시 될 수있다 : 그래서

Dim PathFile As String 
PathFile = Template.Cells(23, 15) '<~ use Template AFTER you set it as a worksheet 

를, 모든 것을 포장하기 이 글을 쓰는 방법에 대한 예제는 다음과 같습니다.

Option Explicit 
Sub PullData() 
Application.ScreenUpdating = False 

Dim PathFile As String 
Dim ClassBook As Workbook 
Dim ClassSheet As Worksheet, Template As Worksheet 

'set references up-front 
Set Template = ThisWorkbook.Worksheets("SomeSheetName") 
PathFile = Template.Cells(23, 15).Value 
Set ClassBook = Workbooks.Open(PathFile & "class" & Format(Now() + 1, "ddmmyy") & "-booked.csv") 
Set ClassSheet = ClassBook.ActiveSheet 

'do work 
Template.Cells(5, 15) = ClassSheet.Cells(2, 1) 

'do other stuff, like close the CSV file or save the Template etc... 

Application.ScreenUpdating = True 
End Sub 
+0

고맙습니다. 실제로 파일을 열지 않고 어떻게 할 수 있습니까? – Petrik

+0

나는 이것을 ClassBook.Close savechanges : = False – Petrik

+0

으로 작성했습니다. @ user3361013 파일을 열어야합니다. 만약 당신이 그것을보고 싶지 않다면, 당신은'Application.ScreenUpdating = False'를 사용할 수 있습니다 (그리고 스크립트의 끝에서'True'로 다시 설정하십시오) –

관련 문제