Cách chuyển dữ liệu từ bảng ra văn bản trong Excel.

Excel là một chương trình xử lý bảng tính tuyệt vời. Excel được tích hợp rất nhiều tính năng giúp cho người dùng xử lý linh hoạt các dữ liệu. Một trong số các công cụ mạnh mẽ nhất của Excel đó chính là VBA.

VBA được hiểu nôm na là một công cụ cho phép bạn tùy biến các tính năng của Excel.

Một trong số các chương trình mà VBA có thể tạo ra không thể không kể đến vị dụ trong bài viết này. Để minh họa rõ hơn về nội dung này, các bạn hãy nhìn hình ảnh phía dưới đây.

Ở hình ảnh phía trên, các bạn sẽ dễ hình dung hơn việc chúng ta chuẩn bị làm. Các bạn có một bảng data trong Excel và bạn đang muốn làm thế nào trích xuất riêng data ra một file dữ liệu như .txt.

Ở đây chúng ta sẽ sử dụng VBA để thực hiện. Các bạn hãy tham khảo code VBA phía dưới nhé.

Option Explicit

Dim objFso As New FileSystemObject    ' Create FSO object.
Dim objTS As TextStream               ' For TextStream object.

Dim sFolder As String

Private Sub Worksheet_Activate()
    write_to_file
End Sub

Sub write_to_file()

    ' Get used range rows count in your worksheet.
    Dim iTotalRows As Integer
    iTotalRows = Worksheets("sheet1").UsedRange.Rows.Count
        
    ' Get used range columns count in your worksheet.
    Dim iTotalCols As Integer
    iTotalCols = Worksheets("sheet1").UsedRange.Columns.Count
    
    Dim iRowCnt, iColCnt As Integer
    Dim sText As String
    
    ' Iterate (or loop) through each row and column.
    For iRowCnt = 1 To iTotalRows
        For iColCnt = 1 To iTotalCols
            ' Store the data in a variable.
            sText = sText & Worksheets("Sheet1").Cells(iRowCnt, iColCnt) & " "
        Next iColCnt
        
        sText = sText & vbCrLf      ' For next row.
    Next iRowCnt
 
    ' Return a TextStream object using the FSO CreateTextFile() method.
    sFolder = "d:fixtures"
    Set objTS = objFso.CreateTextFile(sFolder & "sample.txt")
    
    objTS.WriteLine sText   ' Finally, write the text in the file.
    
    objTS.Close             ' Close the file.
End Sub

0 0 votes
Article Rating
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x