2011-05-07 5 views
1

나는 접근 할 때 vba로 작업하는 것이 처음이므로이 코드를 작동시키는 데 문제가 있습니다. 그것이하는 일은 선택된 텍스트 파일을 가져와 원본 파일을 목록 상자로 읽는 것입니다. 그런 다음 두 번째 버튼을 누르면 텍스트 파일을 파이프로 구분 된 파일에서 탭으로 구분 된 파일로 변환 한 다음 변경된 파일을 새 목록 상자에 표시합니다. 파이프로 구분 된 파일을 탭으로 구분 된 파일로 변환하고 목록 상자에 결과를 표시하는 방법 VBA

Option Compare Database 
Option Explicit 


Function GetFilenameFromPath(ByVal strPath As String) As String 
' Returns the rightmost characters of a string upto but not including the rightmost '\' 
' e.g. 'c:\winnt\win.ini' returns 'win.ini' 

    If Right$(strPath, 1) <> "\" And Len(strPath) > 0 Then 
     GetFilenameFromPath = GetFilenameFromPath(Left$(strPath, Len(strPath) - 1)) + Right$(strPath, 1) 
    End If 
End Function 

Private Sub Command0_Click() 
Dim fdlg As Office.FileDialog 

    Dim pipe_file As Variant 
    Dim FileName As String 
    Dim fn As Integer 
    Dim varFile As Variant 
    Dim FilePath As String 

    Me.OrigFile.RowSource = "" 
    Me.ConvertFile.RowSource = "" 
    Me.FileName = "" 
    Me.FilePath = "" 
    FileName = "" 



    Set fdlg = Application.FileDialog(msoFileDialogFilePicker) 
    With fdlg 
     .AllowMultiSelect = False 
     .Title = "Select pipe delimited file" 
     .Filters.Clear 
     .Filters.Add "Text Files", "*.txt" 

     If .Show = True Then 
      For Each varFile In .SelectedItems 
       FileName = GetFilenameFromPath(varFile) 
       FilePath = varFile 
      Next varFile 
      Me.FileName = FileName 
      Me.FilePath = FilePath 

      fn = FreeFile 

      Open FileName For Input As #fn 
      Do While Not EOF(fn) 
       Line Input #fn, pipe_file 
       Me.OrigFile.AddItem pipe_file 
      Loop 

      Close #fn 
     Else 
      MsgBox "You clicked Cancel in the file dialog box." 
     End If 
    End With 
End Sub 

Private Sub Convert_File_Click() 
'ByVal OutputFile As String)' 
On Error GoTo error1 
Dim pipe_file As Variant 
Dim ThisString As String 
Dim NewString As String 
Dim A As Integer 
Dim InputFile As String 
InputFile = Me.FilePath 
Open InputFile For Input As #1 

Const FileName = "c:\outputfile.txt" 
Dim my_filenumber As Integer 
my_filenumber = FreeFile 
Open FileName For Output As #2 
'Open OutputFile For Output As #2' 

While Not EOF(1) 
NewString = "" 
Line Input #1, ThisString 
For A = 1 To Len(ThisString) 
If Mid(ThisString, A, 1) = "|" Then 
NewString = NewString & Chr$(9) 
Else 
NewString = NewString & Mid(ThisString, A, 1) 
End If 
Next 

Print #2, ThisString 
Wend 
Do While Not EOF(2) 
Line Input #2, pipe_file 
Me.ConvertFile.AddItem pipe_file 
Loop 
Close #2 
Close #1 
Exit Sub 
error1: 
Close #1 
Close #2 
End Sub 

내가 지금까지 지금 내 문제는 두 번째 버튼 또는 Convert_File_Click() convertfile 내가 업데이트하려고 및 파일 경로있어 목록 상자입니다에 TEXTFILE의 파일 경로를 개최 텍스트 상자입니다 관련되는 것을입니다 가 선택됩니다. 도움을 주시면 감사하겠습니다.

답변

0

좋아요 그래서 나는 경우 다른 사람이 내 결과를 게시 할 거라고 생각 지금이

과 도움이 필요
Function PipeToTab(ByVal OriginalText As String) As String 
'Runs though current line of text stored in original text' 
On Error GoTo error1 
Dim ThisString As String, NewString As String, a As Integer 
NewString = "" 

For a = 1 To Len(OriginalText) 
'checks to see if current char is white space and if it is removes it 
    If Mid(OriginalText, a, 1) = " " Then 
    'checks to see if current char is | and if it is changes it to char$(9) (tab) 
    ElseIf Mid(OriginalText, a, 1) = "|" Then 
     NewString = NewString & Chr$(9) 
    Else 
     NewString = NewString & Mid(OriginalText, a, 1) 
    End If 
Next 
    PipeToTab = NewString 
Exit Function 
error1: 
MsgBox (Err.Description) 

End Function` 

이것은 텍스트 파일의 텍스트를 "|"로 변환하는 기능입니다. 탭에 추가 공백을 제거 할 수 있습니다.

`Private Sub Convert_File_Click() 
    On Error GoTo error1 
    Dim pipe_file As Variant 
    Dim ThisString As String 
    Dim a As Integer 
    Dim rfs, rts, InputFile, wfs, wts, OutputFile As Object 
    Dim InputFileName, OutputFileName, OriginalText, updatedText As String 

    ' File initialization 
    'open the original source file and create the output file with the name desired from textbox. 
    InputFileName = Me.FilePath 'filepath is a textbox that holds the location 
    'and name of where you want the textfile to go 
     Set rfs = CreateObject("Scripting.FileSystemObject") 
     Set InputFile = rfs.GetFile(InputFileName) 


    'open the text streams 
     Set rts = InputFile.OpenAsTextStream(1, -2) 'Read 
     Set wts = OutputFile.OpenAsTextStream(8, -2) 'Append 

    'then put line into conversion function and get the updated text 
    'move onto the next line until EOF 

     While rts.AtEndofStream = False 
      OriginalText = rts.ReadLine 'read current line of file 
      If OriginalText <> Empty Then 
       updatedText = PipeToTab(OriginalText) 
       wts.WriteLine updatedText 'put updated text into newly created file(output file) 
      Else 
      End If 
     Wend` 
'Output file clean up 
    wts.Close 
'Input File clean up 
    rts.Close 


End If 
'clear out filestreams 
    Set OutputFile = Nothing 
    Set wfs = Nothing 
    Set wts = Nothing 
    Set InputFile = Nothing 
    Set rfs = Nothing 
    Set rts = Nothing 

Exit Sub 
error1: 
' File Clean up 
rts.Close 
Set InputFile = Nothing 
Set rfs = Nothing 
Set rts = Nothing 

'Output 
wts.Close 
Set OutputFile = Nothing 
Set wfs = Nothing 
Set wts = Nothing 
MsgBox (Err.Description) 
End Sub 

여기는 텍스트 파일을 변환하는 데 사용되는 버튼입니다. 필자는 텍스트 파일의 각 줄을 탭 기능으로 파이프로 보내기 위해 텍스트 스트림과 라인 리더를 사용했습니다.

2

내가 적절하게이 문제를 테스트 할 기회가 없었어요,하지만 더 당신이 찾고있는 무슨 라인에 아마도 :

또한
Private Sub Convert_File_Click() 
    On Error GoTo error_hander 

    Dim pipe_file As Variant 
    Dim ThisString As String 
    Dim NewString As String 
    Dim InputFile As String 
    Dim inputFileNo As Integer 
    Dim outputFileNo As Integer 
    Dim inputFileNo2 As Integer 
    Const FileName = "c:\outputfile.txt" 

    InputFile = Me.FilePath 

    inputFileNo = FreeFile 
    Open InputFile For Input As #inputFileNo 

    outputFileNo = FreeFile 
    Open FileName For Output As #outputFileNo 


    While Not EOF(inputFileNo) 
     Line Input #inputFileNo, ThisString 
     'Nix the FOR LOOP and use the Replace command instead. Less code and easier to understand 
     Print #outputFileNo, Replace(ThisString, "|", vbTab) 
    Wend 
    Close #outputFileNo 

    inputFileNo2 = FreeFile 
    Open FileName For Input As #inputFileNo2 

    Do While Not EOF(inputFileNo2) 
     Line Input #inputFileNo2, pipe_file 
     Me.ConvertFile.AddItem pipe_file 
    Loop 

    GoTo convert_file_click_exit 
error_hander: 
    'Do some error handling here 

convert_file_click_exit: 
    Close #inputFileNo 
    Close #outputFileNo 
End Sub 

, 도움말하지만 GetFilenameFromPath 루틴을 알 수 없었다. 대신 이것을 고려 : 나는 마침내 그것을 알아 낸 것이 시간과 디버깅 많은 연구 시간을 보낸 이후 있도록

Public Function GetFilenameFromPath(ByVal strPath As String) As String 
' Returns the rightmost characters of a string upto but not including the rightmost '\' 
' e.g. 'c:\winnt\win.ini' returns 'win.ini' 

    'There's a couple of ways you could do this so it's not so cumbersome: 
    '1. The DIR command (will return the name of the file if it is a valid directory and file: 
    GetFilenameFromPath = Dir(strPath, vbNormal) 
    '  OR 
    '2. InstrRev 
    Dim iFilePositionStart As Integer 
    iFilePositionStart = InStrRev(strPath, "\", -1, vbTextCompare) 
    GetFilenameFromPath = Mid$(strPath, iFilePositionStart + 1) 


End Function 
관련 문제