空格分隔'导出到文本'Excel宏问题

时间:2010-01-15 20:56:56

标签: excel vba excel-vba delimited-text

我有以下 vba宏将所选单元格导出到文本文件中。问题似乎是分隔符。

我需要一切都处于准确的位置。我将每列的宽度设置为正确的宽度( 9,对于9,如SSN ),我在Excel工作表中将单元格字体设为Courier New( 9pt )。

当我运行它时,它出现真的接近我需要的但是它似乎不处理宽度上只有一个空格的列。

我会将整个方法(和附带的功能)放在底部以供参考,但首先我要发布我认为的部分是我需要关注的地方。我只是不知道以什么方式......

这是我相信我的问题所在(分隔符设置为delimiter = "" - >

' Loop through every cell, from left to right and top to bottom.
  For RowNum = 1 To TotalRows
     For ColNum = 1 To TotalCols
        With Selection.Cells(RowNum, ColNum)
        Dim ColWidth As Integer
        ColWidth = Application.RoundUp(.ColumnWidth, 0)
        ' Store the current cells contents to a variable.
        Select Case .HorizontalAlignment
           Case xlRight
              CellText = Space(Abs(ColWidth - Len(.Text))) & .Text
           Case xlCenter
              CellText = Space(Abs(ColWidth - Len(.Text)) / 2) & .Text & _
                         Space(Abs(ColWidth - Len(.Text)) / 2)
           Case Else
              CellText = .Text & Space(Abs(ColWidth - Len(.Text)))
        End Select
        End With


' Write the contents to the file.
   ' With or without quotation marks around the cell information.
            Select Case quotes
               Case vbYes
                  CellText = Chr(34) & CellText & Chr(34) & delimiter
               Case vbNo
                  CellText = CellText & delimiter
            End Select
            Print #FNum, CellText;

   ' Update the status bar with the progress.
            Application.StatusBar = Format((((RowNum - 1) * TotalCols) _
               + ColNum) / (TotalRows * TotalCols), "0%") & " Completed."

   ' Loop to the next column.
         Next ColNum
   ' Add a linefeed character at the end of each row.
         If RowNum <> TotalRows Then Print #FNum, ""
   ' Loop to the next row.
      Next RowNum

这是整个SHEBANG !作为参考,原件是HERE

Sub ExportText()
'
' ExportText Macro
'
Dim delimiter As String
   Dim quotes As Integer
   Dim Returned As String


  delimiter = ""

  quotes = MsgBox("Surround Cell Information with Quotes?", vbYesNo)



' Call the WriteFile function passing the delimiter and quotes options.
      Returned = WriteFile(delimiter, quotes)

   ' Print a message box indicating if the process was completed.
      Select Case Returned
         Case "Canceled"
            MsgBox "The export operation was canceled."
         Case "Exported"
            MsgBox "The information was exported."
      End Select

   End Sub

   '-------------------------------------------------------------------

   Function WriteFile(delimiter As String, quotes As Integer) As String

   ' Dimension variables to be used in this function.
   Dim CurFile As String
   Dim SaveFileName
   Dim CellText As String
   Dim RowNum As Integer
   Dim ColNum As Integer
   Dim FNum As Integer
   Dim TotalRows As Double
   Dim TotalCols As Double


   ' Show Save As dialog box with the .TXT file name as the default.
   ' Test to see what kind of system this macro is being run on.
   If Left(Application.OperatingSystem, 3) = "Win" Then
      SaveFileName = Application.GetSaveAsFilename(CurFile, _
      "Text Delimited (*.txt), *.txt", , "Text Delimited Exporter")
   Else
       SaveFileName = Application.GetSaveAsFilename(CurFile, _
      "TEXT", , "Text Delimited Exporter")
   End If

   ' Check to see if Cancel was clicked.
      If SaveFileName = False Then
         WriteFile = "Canceled"
         Exit Function
      End If
   ' Obtain the next free file number.
      FNum = FreeFile()

   ' Open the selected file name for data output.
      Open SaveFileName For Output As #FNum

   ' Store the total number of rows and columns to variables.
      TotalRows = Selection.Rows.Count
      TotalCols = Selection.Columns.Count

   ' Loop through every cell, from left to right and top to bottom.
      For RowNum = 1 To TotalRows
         For ColNum = 1 To TotalCols
            With Selection.Cells(RowNum, ColNum)
            Dim ColWidth As Integer
            ColWidth = Application.RoundUp(.ColumnWidth, 0)
            ' Store the current cells contents to a variable.
            Select Case .HorizontalAlignment
               Case xlRight
                  CellText = Space(Abs(ColWidth - Len(.Text))) & .Text
               Case xlCenter
                  CellText = Space(Abs(ColWidth - Len(.Text)) / 2) & .Text & _
                             Space(Abs(ColWidth - Len(.Text)) / 2)
               Case Else
                  CellText = .Text & Space(Abs(ColWidth - Len(.Text)))
            End Select
            End With
   ' Write the contents to the file.
   ' With or without quotation marks around the cell information.
            Select Case quotes
               Case vbYes
                  CellText = Chr(34) & CellText & Chr(34) & delimiter
               Case vbNo
                  CellText = CellText & delimiter
            End Select
            Print #FNum, CellText;

   ' Update the status bar with the progress.
            Application.StatusBar = Format((((RowNum - 1) * TotalCols) _
               + ColNum) / (TotalRows * TotalCols), "0%") & " Completed."

   ' Loop to the next column.
         Next ColNum
   ' Add a linefeed character at the end of each row.
         If RowNum <> TotalRows Then Print #FNum, ""
   ' Loop to the next row.
      Next RowNum

   ' Close the .prn file.
      Close #FNum

   ' Reset the status bar.
      Application.StatusBar = False
      WriteFile = "Exported"
   End Function

进一步发现

我发现下面的Case xlCenter有问题。这是星期五,我还没有能够绕过它,但无论它在case正在做什么就是删除了“”。我通过将所有列设置为Left Justified来验证这一点,以便使用Case Else代替VIOLA!我的空间依旧。我想理解为什么但最终它是A)工作和B)e.James的解决方案无论如何都看起来更好。

感谢您的帮助。

Dim ColWidth As Integer
        ColWidth = Application.RoundUp(.ColumnWidth, 0)
        ' Store the current cells contents to a variable.
        Select Case .HorizontalAlignment
           Case xlRight
              CellText = Space(Abs(ColWidth - Len(.Text))) & .Text
           Case xlCenter
              CellText = Space(Abs(ColWidth - Len(.Text)) / 2) & .Text & _
                         Space(Abs(ColWidth - Len(.Text)) / 2)
           Case Else
              CellText = .Text & Space(Abs(ColWidth - Len(.Text)))
        End Select

2 个答案:

答案 0 :(得分:1)

我认为问题源于您使用列宽作为要使用的字符数。当我在Excel中将列宽设置为1.0时,该列中显示的任何数字都会消失,VBA显示这些单元格的.Text属性为“”,这是有道理的,因为.Text属性为您提供Excel中可见的确切文本。

现在,您有几个选择:

  1. 使用.Value属性而不是.Text属性。这种方法的缺点是它将丢弃您在电子表格中应用的任何数字格式(我不确定这是否是您的问题)

  2. 不是使用列宽,而是在电子表格的顶部放置一行值(在第1行中)以指示每列的相应宽度,然后在VBA代码中使用这些值而不是列宽度。然后,您可以在Excel中使列更宽一些(以便正确显示文本)

  3. 我可能会选择#2但是,当然,我对你的设置知之甚少,所以我不能肯定地说。

    编辑:以下解决方法可能会解决问题。我修改了您的代码以使用每个单元格的ValueNumberFormat属性,而不是使用.Text属性。这应该解决单字符宽单元格的问题。

    With Selection.Cells(RowNum, ColNum)
    Dim ColWidth As Integer
    ColWidth = Application.RoundUp(.ColumnWidth, 0)
    '// Store the current cells contents to a variable.'
    If (.NumberFormat = "General") Then
        CellText = .Text
    Else
        CellText = Application.WorksheetFunction.Text(.NumberFormat, .value)
    End If
    Select Case .HorizontalAlignment
      Case xlRight
        CellText = Space(Abs(ColWidth - Len(CellText))) & CellText
      Case xlCenter
        CellText = Space(Abs(ColWidth - Len(CellText)) / 2) & CellText & _
                   Space(Abs(ColWidth - Len(CellText)) / 2)
      Case Else
        CellText = CellText & Space(Abs(ColWidth - Len(CellText)))
    End Select
    End With
    

    更新:为了解决中心问题,我会做以下事情:

    Case xlCenter
      CellText = Space(Abs(ColWidth - Len(CellText)) / 2) & CellText
      CellText = CellText & Space(ColWidth - len(CellText))
    

    这样,文本右侧的填充将自动覆盖剩余空间。

答案 1 :(得分:0)

您是否尝试将其保存为空格分隔符?我的理解是它将列宽度视为空格数,但尚未尝试所有方案。使用Excel 2007执行此操作似乎对我有用,或者我对您的问题不够了解。我尝试使用width = 1的列,并在生成的文本文件中将其渲染为1个空格。

ActiveWorkbook.SaveAs Filename:= _
    "C:\Book1.prn", FileFormat:= _
    xlTextPrinter, CreateBackup:=False