[英]MS Excel VB export data to text file
Is there a way using Excel macros in Windows to: 有没有一种方法可以在Windows中使用Excel宏来执行以下操作:
.txt
file name using value or content of a cell say A1
. A1
创建.txt
文件名。 It could be alphanumeric. sheet1
and data is in sheet2
, the data contains quotes singe or double and pipe, which should not be affected on export. sheet1
,数据位于sheet2
,数据包含单引号,双引号和“管道”,这在导出时不会受到影响。 Please suggest. 请提出建议。
Sub Export()
Dim rc As Variant
Dim s As String
s = ActiveWorkbook.Path & "\Hello World.txt"
Range("B:B").Copy
MakeTXTFile s
rc = Shell("notepad " & s, 1)
Kill s
End Sub
Sub MakeTXTFile(filePath As String, str As String)
Dim hFile As Integer
If Dir(FolderPart(filePath), vbDirectory) = "" Then
MsgBox filePath, vbCritical, "Missing Folder"
Exit Sub
End If
hFile = FreeFile
Open filePath For Output As #hFile
If str <> "" Then Print #hFile, str
Close hFile
End Sub
Function FolderPart(sPath As String) As String
FolderPart = Left(sPath, InStrRev(sPath, "\"))
End Function
Function getClipboard()
'Add Reference: 'Reference: Microsoft Forms xx Object
Dim MyData As DataObject
On Error Resume Next
Set MyData = New DataObject
MyData.GetFromClipboard
getClipboard = MyData.GetText
End Functionb
I used above code. 我用上面的代码。
The code shall be something like that: 代码应该是这样的:
Sub Export()
Dim rc As Variant
Dim s As String
Dim fso As Object
Set fso = CreateObject("Scripting.FileSystemObject")
Dim oFile As Object
If (ActiveSheet.Name <> "Sheet1") Then
MsgBox ("Error: Wrong Sheet")
Exit Sub
End If
s = MyDocs & "\" & Range("A1").Value & ".txt"
Set oFile = fso.CreateTextFile(s)
For Each xx In Range("B:B")
If xx.Value <> "" Then oFile.WriteLine xx
Next
oFile.Close
Set fso = Nothing
Set oFile = Nothing
MsgBox ("Saved in: " & s)
rc = Shell("notepad " & s, 1)
' Kill s
End Sub
It's not clear the point 6. I put a check, inside you can put what you want... 不清楚要点6。我放了一张支票,里面可以放你想要的东西...
In this code there isn't check for the filename 在此代码中,不检查文件名
Try to use the OLD method... 尝试使用OLD方法...
Dim rc As Variant
Dim s As String
Dim xx
If (ActiveSheet.Name <> "Sheet1") Then
MsgBox ("Error: Wrong Sheet")
Exit Sub
End If
s = MyDocs & "\" & Range("A1").Value & ".txt"
Open s For Output As #1
For Each xx In Range("B:B")
If xx.Value <> "" Then Print #1, xx
Next
Close #1
MsgBox ("Saved in: " & s)
rc = Shell("notepad " & s, 1)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.