[英]How to transfer data from a text file to a specific cell in Excel via VBA?
我有将数据从文本文件传输到 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
但我想将数据传输到 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
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
这个从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
它是通过循环完成的:
While Not EOF(myFile)
Line Input #myFile, textLine
writing = writing & vbCrLf & textLine
Wend
它将每一行写入变量writing
,在需要时添加新行( VbCrLf
是新行)。 最后Worksheets(1).Cells(4, "C").Value = writing
将文件的文本写入工作表C4
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.