txt文件分割(一个大txt文件可按字数分割为若干小文件)vba实例

当txt文本文件字数比较多时,读写很不方便,这时我们可借助以下excel vba代码实现txt文件的分割,分割后每个文件的字数及总文件的路径及全名只需在代码中替换即可。

复制代码
Sub split_txtfile()
Dim bigfile As String, smallfile As String
Dim current_line As String, all_line As String
Dim file_count As Integer, wordcount As Integer
wordcount = 20000 ''分割后每个文件的字节数,可自己修改
''总文件的完整路径及名称需在下行代码进行替换
''以下为调用excel内置api
On Error Resume Next
With Application.FileDialog(msoFileDialogOpen)
    .Title = "请选择你要的文件"
    .AllowMultiSelect = True
    .InitialFileName = "C:\Users\Administrator\Desktop\"
    .Filters.Clear
    .Filters.Add "all files", "*.txt,*.xls,*.xlsx,*.dwg"
    If .Show = True Then
    Set gof = .SelectedItems
    bigfile_fullname = gof.Item(1)
 
    Else: Exit Sub
    End If
End With
''上面从on error resume next 行开始到此行为excel内置打开对话框的函数,如果不用excel vba,可删除上面代码,
''手工录入文件路径及全程 bigfile_fullname =  "C:\Users\Administrator\Desktop\*.txt"
Open bigfile_fullname For Input As #1
Do While Not EOF(1)
  Line Input #1, current_line
  If all_line <> "" Then
       all_line = all_line & vbCrLf & current_line
   Else
      all_line = current_line
   End If
  
  If Len(all_line) > wordcount Then
    file_count = file_count + 1
    small_file = Left(bigfile_fullname, Len(bigfile_fullname) - 4) & "_" & file_count & ".txt"
    Open small_file For Output As #2
    Print #2, all_line
    Close #2
    all_line = ""
  End If

Loop
If all_line <> "" Then
    file_count = file_count + 1
    small_file = Left(bigfile_fullname, Len(bigfile_fullname) - 4) & "_" & file_count & ".txt"
    Open small_file For Output As #2
    Print #2, all_line
    Close #2
    all_line = ""
End If
 Close #1
 MsgBox "txt分割已完成" & Space(50) & vbCr & _
 "vba代码二次开发qq:443440204", vbInformation, "版权所有qq:443440204"
End Sub

本文附有xlsm文件可供下载参考使用。

相关推荐
2401_cf1 小时前
为什么hadoop不用Java的序列化?
java·hadoop·eclipse
帮帮志1 小时前
idea整合maven环境配置
java·maven·intellij-idea
belldeep1 小时前
如何阅读、学习 Tcc (Tiny C Compiler) 源代码?如何解析 Tcc 源代码?
c语言·开发语言
LuckyTHP1 小时前
java 使用zxing生成条形码(可自定义文字位置、边框样式)
java·开发语言·python
Trent19852 小时前
影楼精修-肤色统一算法解析
图像处理·人工智能·算法·计算机视觉
feifeigo1232 小时前
高光谱遥感图像处理之数据分类的fcm算法
图像处理·算法·分类
北上ing3 小时前
算法练习:19.JZ29 顺时针打印矩阵
算法·leetcode·矩阵
无声旅者4 小时前
深度解析 IDEA 集成 Continue 插件:提升开发效率的全流程指南
java·ide·ai·intellij-idea·ai编程·continue·openapi
.格子衫.4 小时前
真题卷001——算法备赛
算法
XiaoyaoCarter4 小时前
每日一道leetcode
c++·算法·leetcode·职场和发展·二分查找·深度优先·前缀树