VBA 쓰기 텍스트 파일 | VBA 코드를 사용하여 텍스트 파일에 Excel 데이터 쓰기

Excel VBA 쓰기 텍스트 파일

VBA에서는 텍스트 파일을 열거 나 읽거나 쓸 수 있습니다. VBA의 파일 시스템 개체 속성을 사용하고 다른 하나는 VBA에서 열기 및 쓰기 메서드를 사용하는 것입니다.

대부분의 기업에서는 보고서가 완성되면 보고서를 데이터베이스에 업로드하려고합니다. 데이터베이스에 업로드하려면 "텍스트 파일"형식을 사용하여 데이터베이스를 업데이트합니다. 일반적으로 Excel에서 데이터를 복사하여 텍스트 파일에 붙여 넣습니다. 우리가 텍스트 파일에 의존하는 이유는 가볍고 간단한 방법으로 인해 작업하기가 매우 쉽기 때문입니다. VBA 코딩을 사용하면 Excel 파일에서 텍스트 파일로 데이터를 복사하는 작업을 자동화 할 수 있습니다. 이 기사에서는 VBA 코드를 사용하여 Excel 파일에서 텍스트 파일로 데이터를 복사하거나 쓰는 방법을 보여줍니다.

VBA를 사용하여 텍스트 파일에 데이터를 쓰는 방법은 무엇입니까?

Excel에서 텍스트로 데이터를 작성하는 것은 복잡한 코딩이며 VBA 코딩에 대한 좋은 지식이 필요합니다. Excel에서 텍스트 파일로 데이터를 복사하는 VBA 코드를 작성하려면 아래 단계를 따르십시오.

코드 작성 방법을 보여주기 전에 open 문을 사용하여 텍스트 파일을 여는 방법을 설명하겠습니다.

열린 텍스트 파일의 구문

[파일 경로] 열기, [모드] 용, [파일 번호]로

파일 경로 : 컴퓨터에서 열려고하는 파일의 경로입니다.

모드 : 모드는 텍스트 파일을 열 때 사용할 수있는 컨트롤입니다. 텍스트 파일에 대해 세 가지 유형의 제어가 가능합니다.

  • 입력 모드 : 여는 텍스트 파일에 대한 " 읽기 전용 "제어를 제안 합니다. "입력 모드"를 사용하면 파일로 아무것도 할 수 없습니다. 텍스트 파일의 내용 만 읽을 수 있습니다.
  • 출력 모드 : 이 옵션을 사용하여 내용을 쓸 수 있습니다. 여기서 기억해야 할 점은 모든 기존 데이터를 덮어 쓴다는 것입니다. 따라서 오래된 데이터의 손실 가능성을주의해야합니다.
  • Append Mode : 이 모드는 OutPut 모드 와 완전히 반대입니다 . 이 방법을 사용하면 실제로 파일의 기존 데이터 끝에 새 데이터를 쓸 수 있습니다.

파일 번호 : 열려있는 모든 텍스트 파일의 텍스트 파일 번호를 계산합니다. 이것은 1에서 511까지의 정수 값으로 열린 파일 번호를 인식합니다. 파일 번호를 할당하는 것은 까다로운 일이며 많은 혼란을 초래합니다. 이를 위해 무료 파일 기능을 사용할 수 있습니다.

Free File 은 열린 파일의 고유 번호를 반환합니다. 이렇게하면 중복 값없이 고유 한 파일 번호를 할당 할 수 있습니다.

여기에서이 VBA 쓰기 텍스트 파일 템플릿을 다운로드 할 수 있습니다 – VBA 쓰기 텍스트 파일 템플릿

예 1

새 텍스트 파일을 만드는 코드를 작성하려면 아래 단계를 따르십시오.

컴퓨터 저장소에 "Hello.txt"라는 텍스트 파일이 이미 있다고 가정하고 여기에 데이터를 쓰는 방법을 보여 드리겠습니다.

1 단계 : 변수 선언

파일 경로를 문자열로 유지하도록 변수를 선언하십시오.

암호:

 Sub TextFile_Example1 () Dim Path As String End Sub 

2 단계 : 파일 번호 결정

어떤 파일 번호를 확인하기 위해 하나 이상의 변수를 Integer로 선언합니다.

암호:

 Sub TextFile_Example1 () Dim Path As String Dim FileNumber As Integer End Sub 

3 단계 : 파일 경로 할당

이제 Path 변수에 파일 이름과 함께 파일 경로를 할당합니다.

암호:

 Sub TextFile_Example1 () Dim Path As String Dim FileNumber As Integer Path = "D : \ Excel Files \ VBA File \ Hello.txt" '요구 사항에 따라 경로 변경 End Sub 

4 단계 : 자유 파일 기능 할당

이제 파일 번호 변수에 대해 "Free File"기능을 할당하여 고유 한 파일 번호를 저장합니다.

암호:

 Sub TextFile_Example1 () Dim Path As String Dim FileNumber As Integer Path = "D : \ Excel Files \ VBA File \ Hello.txt" '요구 사항에 따라 경로 변경 FileNumber = FreeFile End Sub 

5 단계 : 텍스트 파일 열기

이제 작업 할 텍스트 파일을 열어야합니다. 내가 설명했듯이 텍스트 파일을 열려면 OPEN 문을 사용해야합니다.

6 단계 : 인쇄 / 쓰기 방법 사용

파일이 열리면 그 안에 무언가를 써야합니다. 텍스트 파일을 작성하려면 "Write"또는 "Print"방법을 사용해야합니다.

암호:

 Sub TextFile_Example1 () Dim Path As String Dim FileNumber As Integer Path = "D : \ Excel Files \ VBA File \ Hello.txt" '요구 사항에 따라 경로 변경 FileNumber = FileNumber로 출력 할 FreeFile Open Path Print #FileNumber, " Welcome "Print #FileNumber,"to "Print #FileNumber,"VBA "End Sub 

First, we need to mention the file number (here we have assigned the file through the “FileNumber” variable), then we need to add the content we want to add to a text file.

Step 7: Save and Close Text File

Once the content is written in a text file, we need to save and close the text file.

Code:

 Sub TextFile_Example1() Dim Path As String Dim FileNumber As Integer Path = "D:\Excel Files\VBA File\Hello.txt" 'Change the path as per your requirement FileNumber = FreeFile Open Path For Output As FileNumber Print #FileNumber, "Welcome" Print #FileNumber, "to" Print #FileNumber, "VBA" Close FileNumber End Sub 

Now, run the code this manually or through shortcut excel key F5, it will write the mentioned content in the mentioned text file.

Example #2

Now we will see how to write the data of excel sheet to a text file.

For this example, I have created simple data in excel like below.

Step 1: With the continuation of the old example define two more variables as Integer to find the last row and last column.

Code:

 Sub TextFile_Example2() Dim Path As String Dim FileNumber As Integer Dim LR As Integer Dim LC As Integer End Sub 

Step 2: Find the last used row and column in the worksheet.

Step 3: Now assign the file path and file number.

Step 4: Now use the OPEN statement to open the text file.

Step 5: We need to loop through rows and columns, so declare two more variables as Integer.

Step 6: Now open Loop to loop through the row (For next loop in VBA)

Step 7: Now to loop through columns open one more loop inside the existing loop.

Step 8: We need to write the same line of data until it reaches the last column. So for this apply IF statement in VBA.

Step 9: Now save and close the text file.

This code will write the details to a text file, but to open the text file after written we need to use the below code.

Code:

 Sub TextFile_Example2() Dim Path As String Dim FileNumber As Integer Dim LR As Integer Dim LC As Integer Dim k As Integer Dim i As Integer LR = Worksheets("Text").Cells(Rows.Count, 1).End(xlUp).Row LC = Worksheets("Text").Cells(1, Columns.Count).End(xlToLeft).Column Path = "D:\Excel Files\VBA File\Hello.txt" FileNumber = FreeFile Open Path For Output As FileNumber For k = 1 To LR For i = 1 To LC If i  LC Then Print #FileNumber, Cells(i, k), Else Print #FileNumber, Cells(i, k) End If Next i Next k Close FileNumber Shell "notepad.exe " & Path, vbNormalFocus End Sub 

So, run the code using the F5 key or manually then, it will copy the data like the below.