tags:

views:

29

answers:

1

Hey fellas, I have the following VBA code.

It gets the values from an Excel sheet and saves them in a Tab-delimeted text file. However, it adds the column headers. How do I just get the values of rows say starting from row 2, cell A1 if the columns are in row 1, cell A1? Thanks.

Sub DoTheExport()
  Dim FileName As Variant
  Dim Sep As String
  FileName = Application.GetSaveAsFilename( _
    InitialFileName:=vbNullString, _
    FileFilter:="Text Files (*.txt),*.txt" _
  )

  If FileName = False Then
    ''# user cancelled, get out
    Exit Sub
  End If
  Sep = vbTab

  Debug.Print "FileName: " & FileName, "Separator: " & Sep

  ExportToTextFile FName:=CStr(FileName), Sep:=CStr(Sep), _
  SelectionOnly:=False, AppendData:=False
End Sub

Public Sub ExportToTextFile(FName As String, _
    Sep As String, SelectionOnly As Boolean, _
    AppendData As Boolean)

  Dim WholeLine As String
  Dim FNum As Integer
  Dim RowNdx As Long
  Dim ColNdx As Integer
  Dim StartRow As Long
  Dim EndRow As Long
  Dim StartCol As Integer
  Dim EndCol As Integer
  Dim CellValue As String


  Application.ScreenUpdating = False
  On Error GoTo EndMacro:
  FNum = FreeFile

  If SelectionOnly = True Then
    With Selection
      StartRow = ActiveSheet.Range("A3").Select
      StartCol = .Cells(1).Column
      EndRow = .Cells(.Cells.Count).Row
      EndCol = .Cells(.Cells.Count).Column
    End With
  Else
    With ActiveSheet.UsedRange
      StartRow = .Cells(3).Row
      StartCol = .Cells(1).Column
      EndRow = .Cells(.Cells.Count).Row
      EndCol = .Cells(.Cells.Count).Column
    End With
  End If

  If AppendData = True Then
    Open FName For Append Access Write As #FNum
  Else
    Open FName For Output Access Write As #FNum
  End If

  For RowNdx = StartRow To EndRow
    WholeLine = ""
    For ColNdx = StartCol To EndCol
      If Cells(RowNdx, ColNdx).Value = "" Then
        CellValue = Chr(34) & Chr(34)
      Else
        CellValue = Cells(RowNdx, ColNdx).Value
      End If
      WholeLine = WholeLine & CellValue & Sep
    Next ColNdx
    WholeLine = Left(WholeLine, Len(WholeLine) - Len(Sep))
    Print #FNum, WholeLine
  Next RowNdx

EndMacro:
  On Error GoTo 0
  Application.ScreenUpdating = True
  Close #FNum

End Sub
+1  A: 

Why is it not just a matter of changing:

For RowNdx = StartRow To EndRow

to:

For RowNdx = StartRow+1 To EndRow

That will start writing the rows starting with the second one in the range. If you want to auto-detect whether the starting row has column headers, then you will need to check the first cell in the range (using .Value probably) and figure out how to tell the difference between a column header and a value.

paxdiablo