Re: [算表] 如何在特定字串內插入所需之字串??---VBA
如果前一個方法不知如何使用,可以用以下 VBA 的方法,作用完全一樣,
VBA的使用法請查詢之前的文章囉 ...
Option Explicit
Sub Macro1()
Dim path As String
Dim line As Integer
Dim myFile
Dim OriginalText As String, ReplaceText As String
Dim myFso: Set myFso = CreateObject("Scripting.FileSystemObject")
path = "c:\tt\"
line = 3
OriginalText = ".csv"
ReplaceText = "#20040632#.csv"
Dim myfiles: Set myfiles = myFso.GetFolder(path).Files
For Each myFile In myfiles
Call ReplaceFileAtLine(path & myFile.Name, line, _
OriginalText, ReplaceText)
Next
MsgBox ("完成!")
End Sub
Sub ReplaceFileAtLine(myFile As String, line As Integer, _
OText As String, RText As String)
Dim newData As String
Dim index As Integer, index2 As Integer, count As Integer
Dim pre As String, middle As String, last As String
On Error Resume Next
Dim objFSO: Set objFSO = CreateObject("Scripting.FileSystemObject")
index = 1
Dim f1: Set f1 = objFSO.OpenTextFile(myFile)
newData = f1.ReadAll
While count < (line - 1)
index = InStr(index, newData, Chr(13) & Chr(10))
index = index + 1
count = count + 1
Wend
index2 = InStr(index, newData, Chr(13) & Chr(10))
pre = Left(newData, index)
middle = Mid(newData, index + 1, index2 - index - 2)
last = Mid(newData, index2)
middle = Replace(middle, OText, RText)
f1.Close
Set f1 = objFSO.CreateTextFile(myFile)
f1.Write pre & middle & last
f1.Close
End Sub
※ 引述《zeroexe306 ()》之銘言:
: 軟體:Excel
: 版本:2003
: 請教板上的強者大大們
: 若我手上有一堆.csv檔 其內部格式都是固定的
: 第三行的內容為(Notepad版本) Name,,"A090323.csv"
: 若我想在內部插入一字串變成 Name,,"A090323#20040632#.csv"
: 該使用何種方法呢??
: 而且因此檔案是要拿來用程式轉檔用的
: 若直接用Excel開啟改變其內容 會使轉檔程式發生錯誤
: 所以只能用記事本開啟做更改
: 若我內部想要key in的資料都是相同的 (ex:都是插入#20040632#) 且檔案眾多
: 有何較佳的方式嗎??
: 之前有想過用VBA的方式 但是不知道用Notepad開啟檔案與插入字串的語法
: 在此向各位大大請教該如何做呢?? @@
: 在此先謝過了
--
※ 發信站: 批踢踢實業坊(ptt.cc)
◆ From: 61.229.87.124
討論串 (同標題文章)
本文引述了以下文章的的內容:
完整討論串 (本文為第 3 之 3 篇):