我创建了一个Excel文件,该文件包含一个可以执行多项操作的宏。在图像中,您可以看到excel文件的外观。用户将在第12行和第13行输入数据。宏将运行,并将创建使用管道定界符的记事本文件。如您所见,它在文本的第一行上创建了额外的管道-这就是我要摆脱的管道。
Sub NewPipeFile()
Dim IntialName As String
Dim sFileSaveName As Variant
IntialName = "Sample Output"
sFileSaveName = Application.GetSaveAsFilename(InitialFileName:=InitialName, fileFilter:="Excel Files (*.xlsm), *.xlsm")
If sFileSaveName <> False Then
ActiveWorkbook.SaveAs sFileSaveName
End If
'Deletes instructions
Rows("1:11").Select
Range("A11").Activate
Selection.Delete Shift:=xlUp
'Deletes bottom 85 rows so end up with no blank lines
Rows("14:14").Select
ActiveWindow.SmallScroll Down:=90
Rows("14:100").Select
Selection.Delete Shift:=xlUp
'Deletes comments, makes text black, etc
Selection.Font.Bold = False
With Selection.Font
.ColorIndex = xlAutomatic
.TintAndShade = 0
End With
Selection.ClearComments
Const myDelim As String = "|"
Dim ws As Worksheet
Set ws = ActiveSheet
Dim r As Long, c As Long, i As Long, j As Long
r = ws.Cells.Find(What:="*", SearchOrder:=xlByRows, SearchDirection:=xlPrevious).Row
c = ws.Cells.Find(What:="*", SearchOrder:=xlByColumns, SearchDirection:=xlPrevious).Column
Dim myPath As String
myPath = ThisWorkbook.Path & "\"
Dim myFile As String
myFile = myPath & Format(Now(), "yyyy-mm-dd--hh-mm-ss") & "PipeFile.txt"
Dim obj As Object
Set obj = CreateObject("ADODB.Stream")
obj.Type = 2
obj.Charset = "unicode"
obj.Open
Dim v() As Variant
ReDim v(1 To c)
For i = 1 To r
For j = 1 To c
v(j) = ws.Cells(i, j).Text
Next
obj.WriteText Join(v, myDelim), 1
Next
obj.SaveToFile myFile, 2
Dim Npad
Npad = Shell("C:\WINDOWS\notepad.exe " & myFile, 1)
End Sub
答案 0 :(得分:0)
这样的循环:
For i = 1 To r
c = ws.Cells(r,ws.columns.count).end(xlToLeft).column
Dim v as Variant
v = ws.Range(ws.Cells(r,1),ws.Cells(r,c)).Value
objWriteText Join(WorksheetFunction.Transpose(WorksheetFunction.Transpose(v)), myDelim), 1
Next
我在这里使用转置,因为列列表中的列相对较少(因此不会影响速度)。我使用了两次,因为它是基于列的。因此,首先转置是使其基于行,其次是使其变为1D,因为range的默认值为2D数组。