|
分割成指定大小,行数不定,同一行不会分成两个文件,速度快。
- Option Explicit
- Private Sub Form_Click()
- Dim I As Long, FileSize As Long
- Dim FilePath As String
- N = TXT_CUT("D:\123\123.csv", 8000000)
- If N > 0 Then
- MsgBox "共生成文件 " & N & " 个", vbOKOnly, "提示"
- Else
- MsgBox "分割失败,请检查文件及函数参数", vbOKOnly, "提示"
- End If
- End Sub
- Public Function TXT_CUT(sFileName As String, lLength As Long) As Long
- '函数功能:快速将指定文件分割成指定大小文件,生成的文件保存于原文件目录。
- 'sFileName:文件全路径。
- 'lLength: 分割后单个文件大小,单位<字节> 。
- 'TXT_CUT: 返回最终分割出的文件个数。
- Dim sStr() As Byte, ssstr() As Byte
- Dim lSize As Long, FileNumber1 As Long, FileNumber2 As Long
- Dim I As Long, J As Long, K As Long, N As Long
- Dim FileName As String, sPath As String, FileType As String
- If Dir(sFileName) = "" Then Exit Function
- ReDim ssstr(lLength - 1)
- sPath = Left(sFileName, InStrRev(sFileName, ".") - 1)
- FileType = Mid(sFileName, InStrRev(sFileName, "."))
- FileNumber1 = FreeFile
- Open sFileName For Binary As FileNumber1
- lSize = LOF(FileNumber1)
- For I = 0 To lSize \ lLength - 1
- ReDim sStr(lLength - 1)
- Get FileNumber1, I * lLength + 1, sStr
- FileNumber2 = FreeFile
- FileName = sPath & "-" & I + 1 & FileType
- If Dir(FileName) <> "" Then Kill FileName
- Open FileName For Binary As FileNumber2
- For K = ssstr(0) - N To 1 Step -1
- Put FileNumber2, , ssstr(K)
- Next
- ssstr(0) = 0
- For J = UBound(sStr) To 0 Step -1
- ssstr(0) = ssstr(0) + 1
- ssstr(ssstr(0)) = sStr(J)
- If sStr(J) = 10 Or sStr(J) = 13 Then
- N = 1
- If sStr(J - 1) = 10 Or sStr(J - 1) = 13 Then
- N = 2
- ssstr(0) = ssstr(0) + 1
- ssstr(ssstr(0)) = sStr(J - 1)
- Exit For
- Else
- Exit For
- End If
- End If
- Next
- ReDim Preserve sStr(UBound(sStr) - ssstr(0))
- Put FileNumber2, , sStr
- Close FileNumber2
- Next
- ReDim sStr(lSize - I * lLength - 1)
- Get FileNumber1, I * lLength + 1, sStr
- FileNumber2 = FreeFile
- FileName = sPath & "-" & I + 1 & ".csv"
- If Dir(FileName) <> "" Then Kill FileName
- Open FileName For Binary As FileNumber2
- For K = ssstr(0) - N To 1 Step -1
- Put FileNumber2, , ssstr(K)
- Next
- Put FileNumber2, , sStr
- Close FileNumber2
- Close FileNumber1
- TXT_CUT = I + 1
- End Function
复制代码 |
|