将一系列值复制到外部 .txt 行 VBA
Copy a range of values into an external .txt line VBA
我有一个 Excel 工作表,我需要将一系列值复制到给定行的外部 .txt
文件中。 (例如,复制单元格 A1:A7 的值,并将它们粘贴到预先存在的 .txt
文件的第 100 行。我能够 select 值的范围,但是我无法粘贴到特定行。有什么想法吗?
This is a hack:
Public Const FPath = "C:\Temp\YourFile.txt"
Sub test()
Dim fso As New Scripting.FileSystemObject
Dim txtFile As Scripting.TextStream
Dim val As String
Dim valArr() As Variant, v As Variant
valArr = Sheet1.Range("A1:A7").Value2
Dim count As Long
For count = LBound(valArr) To UBound(valArr)
'choose your delimiter, I used space
val = val & IIf(count = LBound(valArr), "", " ") & valArr(count, 1)
Next count
Set txtFile = fso.OpenTextFile(FPath, ForReading, False)
Dim txtArr() As String
txtArr = Split(txtFile.ReadAll, vbCrLf)
txtFile.Close
If UBound(txtArr) >= 4 Then 'I am using 5 instead of 100 - change as necessary
txtArr(4) = val
're-write file
Set txtFile = fso.OpenTextFile(FPath, ForWriting, False)
txtFile.Write Join(txtArr, vbCrLf)
txtFile.Close
Else
'append to file if it has less then 5 lines
Set txtFile = fso.OpenTextFile(FPath, ForAppending, False)
txtFile.Write val
txtFile.Close
End If
Set txtFile = Nothing
End Sub
我有一个 Excel 工作表,我需要将一系列值复制到给定行的外部 .txt
文件中。 (例如,复制单元格 A1:A7 的值,并将它们粘贴到预先存在的 .txt
文件的第 100 行。我能够 select 值的范围,但是我无法粘贴到特定行。有什么想法吗?
This is a hack:
Public Const FPath = "C:\Temp\YourFile.txt"
Sub test()
Dim fso As New Scripting.FileSystemObject
Dim txtFile As Scripting.TextStream
Dim val As String
Dim valArr() As Variant, v As Variant
valArr = Sheet1.Range("A1:A7").Value2
Dim count As Long
For count = LBound(valArr) To UBound(valArr)
'choose your delimiter, I used space
val = val & IIf(count = LBound(valArr), "", " ") & valArr(count, 1)
Next count
Set txtFile = fso.OpenTextFile(FPath, ForReading, False)
Dim txtArr() As String
txtArr = Split(txtFile.ReadAll, vbCrLf)
txtFile.Close
If UBound(txtArr) >= 4 Then 'I am using 5 instead of 100 - change as necessary
txtArr(4) = val
're-write file
Set txtFile = fso.OpenTextFile(FPath, ForWriting, False)
txtFile.Write Join(txtArr, vbCrLf)
txtFile.Close
Else
'append to file if it has less then 5 lines
Set txtFile = fso.OpenTextFile(FPath, ForAppending, False)
txtFile.Write val
txtFile.Close
End If
Set txtFile = Nothing
End Sub