Excel VBA保存为不带分隔符的文本文件
我想使用macros将输出表格从excel转换为文本文件,但有可能转换文件没有分隔符? 我现有的代码只能保存为制表符分隔,但我上传文本文件的系统检测到标签空间为多余的字符。
这里是我现有的VBA代码:
Sub SaveAsTXT() Dim parts As Variant parts = Split(ActiveWorkbook.Name, ".") parts(UBound(parts)) = ".txt" ActiveWorkbook.SaveAs Filename:=ActiveWorkbook.Path & "\" & _ Join(parts, "."), FileFormat:=xlTextWindows, CreateBackup:=False End Sub
您需要分隔符或分隔符来区分不同的字段。
在下面的方法中有一个代码,你可以select你的值分隔符任意你想要的。
现在,
字符作为默认的分隔符。
关于下面的代码注意
- rngRange参数:是要在* .txt文件中导出为报表的源范围。
- strSeparator:是你的合适的分隔符,可以在这里定义。
…
sub Report CsvExportRange rngRange:=ThisWorkbook.Worksheets("Sheet1").Range("tblTaxRep"), _ strFileName:="C:\" & ".txt", _ strCharset:="UTF-8", strSeparator:=",", strRowEnd:=vbCrLf, NVC:=False End Sub
Sub CsvExportRange(rngRange As Object, strFileName As String, strCharset, strSeparator As String, strRowEnd As String, NVC As Boolean) 'NVC: _ Null Value Control (If cell contain Null value, suppose reached end of range), d: delimiter Dim rngRow As Range Dim objStream As Object Dim i, lngFR, lngLR As Long 'lngFR: First Row, lngLR: Last Row lngFR = rngRange.SpecialCells(xlCellTypeVisible).Rows(1).row - rngRange.Rows(1).row + 1 lngLR = rngRange.End(xlDown).row - rngRange.Rows(1).row + 1 Set objStream = CreateObject("ADODB.Stream") objStream.Type = 2 objStream.Charset = strCharset objStream.Open For i = lngFR To lngLR If Not (rngRange.Rows(i).EntireRow.Hidden) Then If IIf(NVC, (Cells(i + rngRange.Rows(1).row - 1, _ rngRange.SpecialCells(xlCellTypeVisible).Columns(1).column).Value = vbNullString), False) Then Exit For objStream.WriteText CsvFormatRow(rngRange.Rows(i), strSeparator, strRowEnd) End If Next i objStream.SaveToFile strFileName, 2 objStream.Close End Sub 'CsvExportRange Function CsvFormatRow(rngRow As Variant, strSeparator As String, strRowEnd As String) As String Dim arrCsvRow() As String ReDim arrCsvRow(rngRow.SpecialCells(xlCellTypeVisible).Cells.Count - 1) Dim rngCell As Range Dim lngIndex As Long lngIndex = 0 For Each rngCell In rngRow.SpecialCells(xlCellTypeVisible).Cells arrCsvRow(lngIndex) = CsvFormatString(rngCell.Value, strSeparator) lngIndex = lngIndex + 1 Next rngCell CsvFormatRow = Join(arrCsvRow, strSeparator) & strRowEnd End Function 'CsvFormatRow Function CsvFormatString(strRaw, strSeparator As String) As String Dim boolNeedsDelimiting As Boolean Dim strDelimiter, strDelimiterEscaped As String strDelimiter = """" strDelimiterEscaped = strDelimiter & strDelimiter boolNeedsDelimiting = InStr(1, strRaw, strDelimiter) > 0 _ Or InStr(1, strRaw, chr(10)) > 0 _ Or InStr(1, strRaw, strSeparator) > 0 CsvFormatString = strRaw If boolNeedsDelimiting Then CsvFormatString = strDelimiter & _ Replace(strRaw, strDelimiter, strDelimiterEscaped) & _ strDelimiter End If End Function 'CsvFormatString