使用VBA从excel到文本文件的选择性数据导出

时间:2015-02-16 05:00:17

标签: excel vba excel-vba

目标是将特定行从工作表复制到文本文件。

具体行说(B6:D6,B7:D7和B14:D14,B21:D21)。

Worksheet Image

3 个答案:

答案 0 :(得分:1)

经过几个小时的努力,这个解决方案可能对许多人有用。关键是使用您需要复制的行的命名范围。

Private Sub btnExport_Click()

Dim rng As Range
Dim Sourceworksheet As Worksheet
Dim DestFile As String
Dim cel As Range

'Destination Path to place the text file.

Application.DefaultFilePath = "\\path\"

DestFile = Application.DefaultFilePath & "\Test.txt"

Open DestFile For Output As #1

Set Sourceworksheet = ActiveWorkbook.ActiveSheet
' select the data or rows you need to copy and make it named range.
Set rng = ShAuReport.Range("DataAuReport")


 For Each cel In rng.Cells

 Write #1, cel.Address & "|" & cel.Value2      

 Next cel

Close #1

MsgBox "txt file exported"


End Sub

此致

摩尼

答案 1 :(得分:0)

首先添加对" Microsoft Scripting Runtime"的引用使用" FileSystemObject"(工具 - >参考 - >选中" Microsoft Scripting Runtime"然后单击确定)


Sub WriteToTextFile()
  Dim fs As New FileSystemObject
  Dim rng As Range
  Dim ws As Worksheet
  Set ws = ActiveSheet
  Set txtfile = fs.CreateTextFile(ThisWorkbook.Path & "\test.txt")
  Set rng = Union(ws.Range("B6:D6"), ws.Range("B7:D7"), ws.Range("B14:D14"), ws.Range("B21:D21"))
  For Each r In rng.Areas
      For Each cel In r
         txtfile.Write (cel.Value & " ")
      Next
      txtfile.Write (vbNewLine)
  Next
End Sub
见linnk: ' https://technet.microsoft.com/en-us/library/ee198716.aspx

答案 2 :(得分:0)

Sub WriteToTextFile3()
'THIS VARIATION SEST RANGE BY COLUMN
  Dim fs As New FileSystemObject
  Dim rng As Range
  Dim ws As Worksheet
  Set ws = ActiveSheet
  Set txtfile = fs.CreateTextFile(ThisWorkbook.Path & "\TestAAA.txt")
  Set rng = Sheet1.Range("B2:B21")
  For Each r In rng.Cells
      For Each cel In r
         txtfile.Write (cel.Value & " ")
         txtfile.Write (cel.Offset(0, 1).Value & " ")
         txtfile.Write (cel.Offset(0, 2).Value & " ") 'MORE COLUMNS? ADD OFFSET
         Next cel
      txtfile.Write (vbNewLine)
    Next
End Sub