vba 写入内容到txt
代码的核心内容,首先获得有数据的代码的单元格地址,将单元格的内容赋值给数组。获得本文件地址,在同文件夹下生成txt文件,通过循环将数组中的数据写入txt文件中,保存。
完整的方法,不存在新建,存在后续添加:
Sub WriteTXT(ByVal txt As String) Dim MyFile As Object Dim Name1 As String, Mypath As String, Save_file As String Dim FSO As Object, wt As Object, wj$ Set MyFile = CreateObject("Scripting.FileSystemObject") '输出文件的名称 Name1 = "闪退记录日志" '获得文件路径 Mypath = ThisWorkbook.Path '保存txt文件路径,可修改名称 Save_file = Mypath & "\" & Name1 & ".txt" If MyFile.FileExists(Save_file) = True Then Set FSO = CreateObject("Scripting.FileSystemObject") wj = ThisWorkbook.Path & "\" & "闪退记录日志" & ".txt" '文件路径/名称/后缀 Set wt = FSO.OpenTextFile(wj, 8, True) '第2参数:1读取(默认),2覆盖写入,8非覆盖写入 wt.Write Chr(10) & txt '一次写入"AAAA" Else Open Save_file For Output As #1 Print #1, txt Close #1 End If End Sub
Sub test1() Dim m As Long, n As Long, p As Long, q As Long Dim Name1 As String, Mypath As String, Temp, Save_file, Ss Dim Arr1() '判断A列数据的最后一行 m = Range("a1048576").End(xlUp).Row '转为数组 Arr1 = Range("a1:a" & m) '输出文件的名称 Name1 = "测试" '获得文件路径 Mypath = ThisWorkbook.Path '保存txt文件路径,可修改名称 Save_file = Mypath & "\" & Name1 & ".txt" Ss = "" '循环得到数组中数据组成字符串 For p = LBound(Arr1) To UBound(Arr1) '行内数据分隔,制表符 Temp = Join(Application.Index(Arr1, p), vbTab) '换行 Ss = Ss & Temp & vbCrLf Next '写入txt文件 Open Save_file For Output As #1 Print #1, Ss Close #1 End Sub