简体   繁体   中英

How to transfer data from a text file to a specific cell in Excel via VBA?

I have this code which transfers data from a textfile to an Excel sheet into column C. Here is a code snippet.

Dim my_file As Integer
Dim text_line As String
Dim file_name As String
Dim i As Integer

file_name = "C:\Users\" & Environ("Username") & "\Desktop\Test.txt"

my_file = FreeFile()
Open file_name For Input As my_file

i = 1

While Not EOF(my_file)
    Line Input #my_file, text_line
    Cells(i, "C").Value = text_line
    i = i + 1
Wend

But I want to transfer the data to C4. How can I tweak the code to achieve my objective?

  • Wrtiting the whole file starting from a certain cell C4 and going down with every line

在此处输入图片说明

Sub TestMe()

    Dim myFile As Long
    Dim textLine As String
    Dim fileName As String

    fileName = "C:\Users\" & Environ("Username") & "\Desktop\Test.txt"

    myFile = FreeFile()
    Open fileName For Input As myFile

    Dim writing As String
    Dim i As Long: i = 4
    While Not EOF(myFile)
        Line Input #myFile, textLine
        Worksheets(1).Cells(i, "C").Value = textLine
        i = i + 1
    Wend

End Sub
  • Wrtiting the whole file to a single cell

This one takes all the lines from the Test.txt and writes them into Range("C4") of the first worksheet:

Sub TestMe()

    Dim myFile As Long
    Dim textLine As String
    Dim fileName As String

    fileName = "C:\Users\" & Environ("Username") & "\Desktop\Test.txt"

    myFile = FreeFile()
    Open fileName For Input As myFile

    Dim writing As String

    While Not EOF(myFile)
        Line Input #myFile, textLine
        writing = writing & vbCrLf & textLine
    Wend

    Worksheets(1).Cells(4, "C").Value = writing        

End Sub

It is done through the loop:

While Not EOF(myFile)
    Line Input #myFile, textLine
    writing = writing & vbCrLf & textLine
Wend

which writes every line to the variable writing , adding a new line whenever needed ( VbCrLf is the new line). At the end Worksheets(1).Cells(4, "C").Value = writing writes the text of the file to the worksheet at C4 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM