2015-01-14 3 views
0

나는 내가 일상적으로 별도의 엑셀 워크 시트에 텍스트 파일을 가져 오는 데 사용할 다음 매크로가 있습니다엑셀 매크로

Sub ImportManyTXTs() 
Dim strFile As String 
Dim ws As Worksheet 
strFile = Dir("C:\location\of\folder\with\textfiles\*.txt") 
Do While strFile <> vbNullString 

strFile2 = Replace(strFile, ".txt", "") 

Set ws = Sheets.Add 
With ws.QueryTables.Add(Connection:= _ 
    "TEXT;" & "C:\location\of\folder\with\textfiles\" & strFile, Destination:=Range("$A$1")) 
    .Name = strFile 
    .FieldNames = True 
    .RowNumbers = False 
    .FillAdjacentFormulas = False 
    .PreserveFormatting = True 
    .RefreshOnFileOpen = False 
    .RefreshStyle = xlInsertDeleteCells 
    .SavePassword = False 
    .SaveData = True 
    .AdjustColumnWidth = True 
    .RefreshPeriod = 0 
    .TextFilePromptOnRefresh = False 
    .TextFilePlatform = 437 
    .TextFileStartRow = 1 
    .TextFileParseType = xldelimited 
    .TextFileTextQualifier = xlTextQualifierDoubleQuote 
    .TextFileConsecutiveDelimiter = True 
    .TextFileTabDelimiter = False 
    .TextFileSemicolonDelimiter = False 
    .TextFileCommaDelimiter = False 
    .TextFileSpaceDelimiter = True 
    .TextFileColumnDataTypes = Array(1, 1, 1) 
    .TextFileFixedColumnWidths = Array(7, 9) 
    .TextFileTrailingMinusNumbers = True 
    .Refresh BackgroundQuery:=False 
End With 
ws.Name = strFile2 
strFile = Dir 
Loop 
End Sub 

을 ...하지만 난을 덮어 싶습니다 동일한 이름이 이미 사용 된 경우 기존 워크 시트. 다른 워크 시트에는 워크 시트의 셀에 대한 참조가 있으므로 덮어 쓰지 않아도됩니다. 따라서이 셀에 대한 참조를 깨지 않고이 작업을 수행 할 방법이 필요합니다. 누구든지 이것에 대한 좋은 해결책을 알고 있습니까? 당신을 가정

+0

워크 시트를 덮어 쓰는 경우 해당 참조를 유지하는 데 어떤 의미가 있습니까? 방금 내용을 추가하고 있습니까? – EngJon

+0

텍스트 파일의 데이터가 '업데이트'된 값입니다. 이것은 본질적으로 텍스트 파일의 데이터를 사용하여 워크 시트를 '새로 고침'합니다. – HotDogCannon

+0

아마 새로운 정보를 추가하려고 시도해야합니다. 그렇게하면 이전 워크 시트를 유지하고 참조를 참조 할 수 있습니다. 나는 당신의 코드가 무엇인지 모른다고 인정해야한다. - 쿼리 테이블로는 전혀 작동하지 않는다. -하지만 새로운 정보를 추출 할 수 있다면 쉽게 추가 할 수있는 방법이있을 것이다. – EngJon

답변

1

는 쿼리 테이블 외에 그 시트에 저장된 다른 정보가없는이 시도 (I 잘라 당신의 공간에 대한 문) :이 경우

Sub ImportManyTXTs() 
Dim strFile As String 
Dim Sht As Worksheet 
Dim ws As Worksheet 
strFile = Dir("C:\location\of\folder\with\textfiles\*.txt") 
Do While strFile <> vbNullString 

strFile2 = Replace(strFile, ".txt", "") 

For Each Sht in Worksheets 
    If Sht.Name = strFile2 Then 
     Sht.Cells.ClearContents 
     Set ws = Sht 
    End If 
Next Sht 
If ws Is Nothing Then 
    Set ws = Sheets.Add 
    ws.Name = strFile2 
End If 
ws.Activate 

With ActiveSheet.QueryTables.Add(Connection:= _ 
    'YourStuffHere 
End With 

strFile = Dir 
Loop 
End Sub 

시트의 내용을 것입니다 이미 존재하는 경우 교체 만하면 세포에 대한 참조가 변경되어서는 안됩니다.

+0

'다른 시트, 참조 된 개체 라이브러리 또는 Visual Basic에서 참조하는 통합 문서와 같은 이름으로 시트의 이름을 바꿀 수 없습니다.'라는 줄을 가리킴 'ws.Name = strFile2 ' – HotDogCannon

+0

죄송합니다. 지금 시도하십시오. –

+0

걱정할 필요가 없습니다. 이제 '목적지 범위가 쿼리 테이블이 생성되는 동일한 워크 시트에 있지 않습니다'... 어쩌면 내가 현재 워크 시트를 처방해야합니까 ?? – HotDogCannon