Excel如何用VBA把A1列的内容写入到TXT文本里

Excel如何用VBA把A1列的内容写入到TXT文本里,第1张

sub 宏1()

    dim arr,i

    arr=range("a1").currentregion

    open "1.txt" for output as #1

    for i=1 to ubound(arr)

        print #1, arr(i,1)

    next i

    close #1

end sub

用法:运行代码,结果会生成在excel所在的文件夹下面的output.txt中。如果想指定运算区域,则将,选中你想要挑选的区域,'Set zon = Application.InputBox("please choose the zone", Type:=8)前的 ' 去掉然后添加到 Set zon = Range("A1:Z1000")前面。

Sub output()

Dim zon As Range

Dim ttr, ttc As String

Open ThisWorkbook.Path &"\output.txt" For Output As #1

Set zon = Range("A1:Z1000")

'Set zon = Application.InputBox("please choose the zone", Type:=8)

For Each Rng In zon

If Rng.Font.Color = 255 Then

ttr = Cells(Rng.Row, 1)

ttc = Cells(1, Rng.Column)

Print #1, ttr, ttc, Rng

End If

Next

Close #1

End Sub

建一个文件夹,把目标txt文件和excel文件放入其中,在excel的宏编辑器中写入以下代码,有些地方可根据你的实际情况做相应改动:

Sub import_from_txt()

Dim file_name As String, my_path As String

Dim lines, cols

Dim i As Integer, j As Integer, k As Integer, q As Integer

Application.ScreenUpdating = False

Worksheets("Sheet1").Range("A1:Z65536").ClearContents

my_path = ThisWorkbook.Path

file_name = "test.txt"

'读取文件

Open my_path &"\" &file_name For Input As #1

lines = Split(StrConv(InputB(LOF(1), 1), vbUnicode), vbCrLf)

Close #1

k = UBound(lines) + 1 '文件的行数

'遍历每一行

For i = 1 To k

cols = Split(lines(i - 1), ",") '以逗号作为分隔,将每行字符分割,分隔符可根据实际情况自己修改

q = UBound(cols) + 1 '分隔成的列数

For j = 1 To q '遍历该行的每一列

Worksheets("Sheet1").Cells(i, j) = cols(j - 1) '输出到表格中

Next

Next

MsgBox ("文件" &file_name &"读取完成,共" &k &"行")

Application.ScreenUpdating = True

End Sub


欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/bake/11942615.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2023-05-19
下一篇 2023-05-19

发表评论

登录后才能评论

评论列表(0条)

保存