2010-04-05 2 views
0

.txt 파일에서 데이터를 읽은 다음 .xls 파일에 데이터를 채우는 데 사용하려고하지만, .txt 파일을 연 후 어떻게 데이터를 가져 옵니까? 기본적으로 '04/06/2010 '일자의 세 번째 열을 얻으려고합니다. 을 사용할 때 .txt 파일을 열면 ActiveSheet이 .txt 파일을 가리키고 있지 않습니다.VBA에서 .txt 파일의 데이터를 Excel로 채우는 방법?

내 .txt 파일은 (공간 분리) 이렇게 있습니다 :

여기
04/05/10 23 29226 
04/05/10 24 26942 
04/06/10 1 23166 
04/06/10 2 22072 
04/06/10 3 21583 
04/06/10 4 21390 

코드 나는이된다

Dim BidDate As Date 

BidDate = '4/6/2010' 

Workbooks.OpenText Filename:=ForecastFile, StartRow:=1, DataType:=xlDelimited, Space:=True 

If Err.Number = 1004 Then 
    MsgBox ("The forecast file " & ForecastFile & " was not found.") 
    Exit Sub 
End If 

On Error GoTo 0 


Dim row As Integer, col As Integer 


row = 1 
col = 1 

cell_value = activeSheet.Cells(row, col) 
MsgBox ("the cell_value=" & cell_value) 

Do While (cell_value <> BidDate) And (cell_value <> "") 
    row = row + 1 
    cell_value = activeSheet.Cells(row, col) 
    ' MsgBox ("the value is " & cell_value) 
Loop 

If cell_value = "" Then 
    MsgBox ("A load forecast for " & BidDate & " was not found in your current load forecast file titled '" + ForecastFile + ". " + "Make sure you have a load forecast for the current bid date and then open this spreadsheet again.") 
    ActiveWindow.Close 
    Exit Sub 
End If 

사람이 여기에 잘못 곳을 포인트?

답변

0

아래 예제에서는 변수 ws를 원하는 시트와 같게 설정하고 해당 변수를 사용하여 나중에 시트를 참조 할 수 있습니다. ActiveWorkbook 키워드는 새로 열어 본 텍스트 파일을 가리켜 야합니다. 나는 당신이 정보로 무엇을하고 싶었는지를 말할 수 있었고, 나는 그런 것들을 만들었습니다. 당신이 긍정적 인 아니라면 당신은 일반적으로 ActiveWorkbook 개체를 사용하지 않아야합니다

Sub GetBidData() 

    Dim dtBid As Date 
    Dim ws As Worksheet 
    Dim rFound As Range 
    Dim sFile As String 

    dtBid = #4/6/2010# 
    sFile = Environ("USERPROFILE") & "\My Documents\ForecastFile.txt" 

    Workbooks.OpenText Filename:=sFile, _ 
     StartRow:=1, _ 
     DataType:=xlDelimited, _ 
     Space:=True 
    Set ws = ActiveWorkbook.Sheets(1) 

    Set rFound = ws.Columns(1).Find(_ 
     Format(dtBid, ws.Range("A1").NumberFormat), , xlValues, xlWhole) 

    If Not rFound Is Nothing Then 
     MsgBox rFound.Value & vbCrLf & _ 
      rFound.Offset(0, 1).Value & vbCrLf & _ 
      rFound.Offset(0, 2).Value 
    End If 

End Sub 
+0

형식을 변경 아래 그 I를 추가해야 코드에 오류가 발생하지 않았으므로 아무 것도하지 않는 것 같습니다. –

0

당신이 당신의 코드가 실행될 때 항상 활성화됩니다 참조 할 통합 문서. 대신, 작업중인 통합 문서를 변수로 설정해야합니다. 이론적으로 OpenText 메서드를 사용하여이 작업을 수행 할 수 있어야하지만 VBA에서는이를 사용하지 않습니다. (. 나는 그것이 버그 확신) 당신이 당신의 텍스트 파일을 연 후 너무 좋아, 내가 이런 짓을 했을까 : 대신의 다음

Workbooks.OpenText Filename:=Forecastfile, StartRow:=1, 
    DataType:=xlDelimited, Space:=True 

Dim ForecastWorkbook As Workbook, book As Workbook 
Dim ForecastFileName As String 

ForecastFileName = "YourFileNameHere.txt" 

For Each book In Application.Workbooks 

    If book.Name = ForecastFileName Then 

     Set ForecastWorkbook = book 
     Exit For 

    End If 

Next book 

, ...

cell_value = activeSheet.Cells(row, col) 

을 ... 이것을하십시오 ...

cell_value = ForecastWorkbook.Sheets(1).Cells(row, col).Value 
0

아래 코드는 텍스트 파일을 읽고 Sheet2의 셀에 값을 붙여 넣습니다. 당신은 예를 들어 트릭

Public Sub Read_text() 
Sheet2.Activate 
Set fso = New FileSystemObject 
Fname = Application.GetOpenFilename 
x = 1 
y = 1 
Set Stream = fso.OpenTextFile(Fname, ForReading, True) 
Do While Not Stream.AtEndOfStream 
      Str_text = Stream.ReadLine 'Perform your actions 
      rdtext = Split(Str_text, " ") 
      Sheet2.Cells(x, y) = rdtext(0) 
      Sheet2.Cells(x, y + 1) = rdtext(1) 
      Sheet2.Cells(x, y + 2) = rdtext(2) 
      x = x + 1 
      y = 1 
Loop 
Stream.Close 
End Sub 

을 할 것입니다 날짜 열에서 서식을 넣어 그러나 경우 : 코드는 '05/04/2010 '

Sheet2.Cells(x, y) = Format(rdtext(0), "mm/dd/yyyy;@") 
+0

그냥 코드를 덤프하는 것이 아니라 답을 설명하는 것입니다. –

관련 문제