Excel VBA,另存为.txt时保持格式

克里斯

我将固定宽度的文本文件导入Excel,然后将其导出。我试图弄清楚保存时如何保持格式。
在导入时,我尝试使用.NumberFormat,它在导入时强制格式化,但在导出时会释放格式。

我已导入的文本文件: 我正在导入的文本文件

我的出口惯例:

Option Explicit
Sub CreateFixedWidthFile(strFile As String, ws As Worksheet, s() As Integer)
  Dim i As Long, j As Long
  Dim strLine As String, strCell As String

  'get a freefile
  Dim fNum As Long
  fNum = FreeFile

 'open the textfile
  Open strFile For Output As fNum
 'loop from first to last row
 'use 2 rather than 1 to ignore header row
  For i = 2 To ws.Range("a65536").End(xlUp).Row
    'new line
    strLine = ""
    'loop through each field
    For j = 0 To UBound(s)
      'make sure we only take chars up to length of field (may want to 
      output some sort of error if it is longer than field)
      strCell = Left$(ws.Cells(i, j + 1).Value, s(j))
      'add on string of spaces with length equal to the 
      'difference in length between field length and value length
        strLine = strLine & strCell & String$(s(j) - Len(strCell), Chr$(32))
    Next j
    'write the line to the file
    Print #fNum, strLine
  Next i
 'close the file
  Close #fNum
End Sub

调用它:

Sub CreateFile()
  Dim sPath As String
  sPath = Application.GetSaveAsFilename("", "Text Files,*.txt")
  If LCase$(sPath) = "false" Then Exit Sub
  'specify the widths of our fields
  'the number of columns is the number specified in the line below +1
  Dim s(5) As Integer
 'starting at 0 specify the width of each column
  s(0) = 10
  s(1) = 2
  s(2) = 9
  s(3) = 10
  s(4) = 1
  s(5) = 20
 'write to file the data from the activesheet
  CreateFixedWidthFile sPath, ActiveSheet, s
End Sub

导出的文本文件(请参阅第6列的格式现在是十进制和科学计数法): 出口后

马修·金登(Mathieu Guindon)

您将导出通常要使用以保留实际

如果您希望这些值的字符串表示形式出现在工作表上,则需要导出单元格文本,而不是它们的

strCell = Left$(ws.Cells(i, j + 1).Text, s(j))

请注意,这将失去数值精度,并且您现在将数字视为文本,如果这些值需要再次作为数字处理,则会带来问题。

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

Excel VBA打开Word模板,填充,然后另存为.docx文件

如何在VBA中另存为.txt

另存为不接受包含“。”的字符串。在Excel VBA中

Excel VBA另存为制表符分隔文件

从Outlook打开文件到Excel,并根据发件人另存为其他格式

VBA Excel将新文件另存为活动文件的日期

如何另存为和更改VBA格式文件

Excel VBA UserForm打印屏幕另存为pdf

我可以用Excel中的VBA保存功能替换“保存”或“另存为”按钮吗?

VBA Excel基于图纸颜色另存为PDF-根据标签颜色创建图纸阵列

Excel VBA删除公式并另存为v2

将熊猫另存为Excel文件时,如何使用熊猫插入Excel公式?

将Excel工作表另存为.txt

如何在Excel VBA中将每个工作表的首页另存为PDF

如何使用Excel VBA打开.csv并将其另存为.xlsx

另存为==> Csv时在Excel中出现怪异问题

Excel另存为框

Excel工作簿另存为.pdf

VBA从Access将Excel文件另存为.xls

VBA Excel将副本另存为txt文件

如何另存为excel和vba项目以备将来使用?

使用VBA在Access中将Excel文件另存为文本

VBA-Excel-另存为并删除原始工作簿

Excel VBA另存为不带分隔符的文本文件

Excel VBA另存为名称“MONTH”转换为数字(两位数)

Excel VBA 在默认文件夹中将文件另存为 Word 文档

使用excel VBA在IE中单击“另存为”

将 Excel 文件另存为 txt 时如何防止重复额外的倒转逗号

Excel VBA - 使用通配符或部分匹配打开的工作簿无法另存为副本