[英]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.我有将数据从文本文件传输到 Excel 工作表到 C 列的代码。这是一个代码片段。
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.但我想将数据传输到 C4。 How can I tweak the code to achieve my objective?
如何调整代码以实现我的目标?
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
This one takes all the lines from the Test.txt
and writes them into Range("C4")
of the first worksheet:这个从
Test.txt
获取所有行并将它们写入第一个工作表的Range("C4")
中:
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).它将每一行写入变量
writing
,在需要时添加新行( VbCrLf
是新行)。 At the end Worksheets(1).Cells(4, "C").Value = writing
writes the text of the file to the worksheet at C4
.最后
Worksheets(1).Cells(4, "C").Value = writing
将文件的文本写入工作表C4
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.