2010-02-26 150 views
1

嘿夥計們,我有以下的VBA代碼。VBA宏問題

它從Excel工作表中獲取值並將其保存在製表符分隔的文本文件中。但是,它添加了列標題。如何獲得行的值,從第2行開始,如果列在第1行,單元格A1,單元格A1?謝謝。

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 

回答

2

爲什麼它不只是一個改變的事情:

For RowNdx = StartRow To EndRow 

到:

For RowNdx = StartRow+1 To EndRow 

這將開始寫起與第二個範圍內的行。如果要自動檢測起始行是否有列標題,則需要檢查範圍內的第一個單元格(可能使用.Value),並找出如何區分列標題和值之間的區別。

0

代碼開始行和開始列可能會被新用戶誤解。

StartRow = .Cells(3).Row 
StartCol = .Cells(1).Column 

.Cells語法是將細胞(指數)或細胞(行,列)

例如.Cells(1,2)是指B1如果範圍是片材。然而,小區(3)指的是使用範圍內的第三個小區。如果數據的範圍是
4乘4,如A1到D4,則小區(5)將參考A2。

如果你想在第二行開始,爲什麼不使用

startrow = .Cells(2, 1) 

清楚地表明開始要導出的數據是在第2行,列1.