Пробел в макросе Excel «Экспорт в текст» с разделителями пробелами - PullRequest
4 голосов
/ 15 января 2010

У меня есть ниже vba macro для экспорта выбранных ячеек в текстовый файл. Кажется, проблема в разделителе.

Мне нужно, чтобы все было в точном положении. У меня для каждого столбца установлена ​​правильная ширина ( 9 для 9, например SSN ), и у меня есть шрифт ячеек в виде Courier New ( 9pt ) в листе Excel.

Когда я запускаю это, оно выходит ДЕЙСТВИТЕЛЬНО близко к тому, что мне нужно, но, похоже, оно не имеет дело со столбцами, которые имеют только один пробел по ширине.

Я положу метод ВСЕ ( и сопровождающую функцию ) внизу для справки, но сначала я хотел бы опубликовать часть Я ДУМАЮ где мне нужно сосредоточиться Я просто не знаю, каким образом ...

Именно здесь Я считаю моей проблемой (разделитель установлен на 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

Это ВЕСЬ ШИБАНГ ! Для справки оригинал ЗДЕСЬ .

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, удаляло "". Я подтвердил это, установив для всех столбцов значение «Выровнено по левому краю», чтобы вместо него использовалось Case Else, а «ВИОЛА»! Мое пространство осталось. Я хотел бы понять, почему, но в конце концов это 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 ]

1 голос
/ 16 января 2010

Я думаю, что проблема связана с тем, что вы используете ширину столбца в качестве количества используемых символов. Когда я устанавливаю ширину столбца в 1.0 в Excel, все числа , отображаемые в этом столбце, просто исчезают, и VBA показывает, что свойство .Text для этих ячеек равно "", что имеет смысл, поскольку .Text свойство дает вам точный текст, который виден в Excel.

Теперь у вас есть несколько вариантов здесь:

  1. Используйте свойство .Value вместо свойства .Text. Недостатком этого подхода является то, что он отбрасывает любое форматирование чисел, которое вы применили в электронной таблице (я не уверен, если это проблема в вашем случае)

  2. Вместо использования ширины столбца поместите строку значений в верхней части электронной таблицы (в строке 1), чтобы указать подходящую ширину для каждого столбца, а затем используйте эти значения в коде VBA вместо столбца. ширина. Затем вы можете сделать ваши столбцы немного шире в Excel (чтобы текст отображался правильно)

Я бы, наверное, пошел с # 2, но, конечно, я не очень разбираюсь в вашей настройке, поэтому не могу сказать наверняка.

edit: Следующий обходной путь может помочь. Я изменил ваш код, чтобы использовать свойства Value и NumberFormat каждой ячейки вместо использования свойства .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))

Таким образом, отступы с правой стороны текста будут автоматически покрывать оставшееся пространство.

0 голосов
/ 16 января 2010

Вы пытались просто сохранить его как разделитель пробелов? Насколько я понимаю, он будет обрабатывать ширину столбца как число пробелов, но не пробовал все сценарии. Мне кажется, что делать это с помощью Excel 2007 - или я не совсем понимаю вашу проблему. Я попытался с столбцом с шириной = 1, и он получил 1 пробел в результирующем текстовом файле.

ActiveWorkbook.SaveAs Filename:= _
    "C:\Book1.prn", FileFormat:= _
    xlTextPrinter, CreateBackup:=False
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...