VBA助:如何實現excel與txt之間字符串查找與單元格值的替換
如果你的txt文件使用tab分隔符,那么以下代碼可以符合你的要
SubChangeTxt()
DimFileN,TxtWbAsWorkbook,ToFindDataAsString
DimToSubDataAsString,cAsRange,FirstAdrAsString
IfMsgBox("是否已經選中待查找的單元格?",vbYesNo)=vbNoThenExitSub
ToFindData=Selection.Cells(1).Value
ToSubData=Selection.Cells(1).Offset(,1).Value
FileN=Application.GetOpenFilename("Txt文件,*.txt",,"選擇txt文件")
IfTypeName(FileN)="Boolean"ThenExitSub
Workbooks.OpenTextFilename:=FileN,consecutivedelimiter:=False,_
Tab:=True,Space:=False
SetTxtWb=ActiveWorkbook
Setc=TxtWb.Sheets(1).UsedRange.Find(What:=ToFindData,_
LookAt:=xlPart,MatchCase:=False,matchbyte:=False,SearchFormat:=False)
IfNotcIsNothingThen
FirstAdr=c.Address
Do
c.Offset(,4)=ToSubData
Setc=TxtWb.Sheets(1).UsedRange.FindNext(c)
LoopUntilc.Address=FirstAdr
TxtWb.Closesavechanges:=True
MsgBox"替換完畢"
Else
TxtWb.CloseFalse
MsgBox"未找到,請選中要查找的單元格。"
EndIf
excelvba內容替換
Subs()
DimcAsRange
n=Cells(Rows.Count,"t").End(3).Row
Setrg=Range("b6:t"&n)
rg.HorizontalAlignment=xlCenter
t=InputBox("輸入要查找的數字")
ForEachcInrg
Ifc""Andc"√"Andc"X"Then
IfInStr(c,t)>0Then
c="√"
Else
c="X"
EndIf
EndIf
Next
ForEachcInrg
Ifc="√"Then
c.Font.Bold=True
c.Font.Color=vbBlue
ElseIfc="X"Then
c.Font.Bold=True
c.Font.Color=vbRed
EndIf
Next
EndSub
遍歷工作表查找字符串并替換VBA
Range("A1").Select
Selection.Copy
Cells.Find(What:="*照明*",After:=ActiveCell,LookIn:=xlFormulas,LookAt_
:=xlPart,SearchOrder:=xlByRows,SearchDirection:=xlNext,MatchCase:=_
False,MatchByte:=False,SearchFormat:=False).Activate
Cells.FindNext(After:=ActiveCell).Activate
Cells.FindNext(After:=ActiveCell).Activate
Cells.FindNext(After:=ActiveCell).Activate
Cells.FindNext(After:=ActiveCell).Activate
Cells.FindNext(After:=ActiveCell).Activate
Cells.FindNext(After:=ActiveCell).Activate
ActiveCell.ReplaceWhat:="*照明*",Replacement:="馬尼公司照明*30倍",LookAt:=_
xlPart,SearchOrder:=xlByRows,MatchCase:=False,SearchFormat:=False,_
ReplaceFormat:=False
Cells.FindNext(After:=ActiveCell).Activate
ActiveCell.ReplaceWhat:="*照明*",Replacement:="馬尼公司照明*30倍",LookAt:=_
xlPart,SearchOrder:=xlByRows,MatchCase:=False,SearchFormat:=False,_
ReplaceFormat:=False
Cells.FindNext(After:=ActiveCell).Activate
ActiveCell.ReplaceWhat:="*照明*",Replacement:="馬尼公司照明*30倍",LookAt:=_
xlPart,SearchOrder:=xlByRows,MatchCase:=False,SearchFormat:=False,_
ReplaceFormat:=False
Cells.FindNext(After:=ActiveCell).Activate
ActiveCell.ReplaceWhat:="*照明*",Replacement:="馬尼公司照明*30倍",LookAt:=_
xlPart,SearchOrder:=xlByRows,MatchCase:=False,SearchFormat:=False,_
ReplaceFormat:=False
Cells.FindNext(After:=ActiveCell).Activate
ActiveCell.ReplaceWhat:="*照明*",Replacement:="馬尼公司照明*30倍",LookAt:=_
xlPart,SearchOrder:=xlByRows,MatchCase:=False,SearchFormat:=False,_
ReplaceFormat:=False
Cells.FindNext(After:=ActiveCell).Activate
以上就是VBA教程:在Excel和文本文件之間進行字符串搜索和單元格值替換的方法的詳細內容,!