我需要一些帮助来解决我编写的宏的问题,如果用户输入字符串存在,该宏将删除csv或txt文件中的行。
我已经声明了File1
,File2
,File3
等变量,这些变量基于输入文本文件,该文件始终具有需要搜索的不同文件路径。这部分代码有效。
该代码的下一部分应该查看每个文件的文件扩展名,并基于此调用正确的过程。
当我在前四个为.csv而第五个为.txt的某些文件上运行代码时,csv文件中什么也没有发生,但第5个文件另存为第4个文件。
有人能在这里看到我做错了吗?下面的代码段:
Application.ScreenUpdating = False
Application.Calculation = xlCalculationManual
Application.EnableEvents = False
Dim myOutput As String:
myOutput = "G:\Team Drives\Technology Team\Data Management\Admin\GDPR\tempoutput.txt"
If File1 <> "" Then
If Right$(File1, 3) = "csv" Then
Workbooks.Open File1
Call cleanCSV
Else
Open File1 For Input As #1
Call cleanTXT
File1.Close
ActiveWorkbook.Close
Kill myOutput
End If
End If
If File2 <> "" Then
If Right$(File2, 3) = "csv" Then
Workbooks.Open File2
Call cleanCSV
Else
Open File2 For Input As #1
Call cleanTXT
File2.Close
ActiveWorkbook.SaveAs fileName:=File2
ActiveWorkbook.Close
Kill myOutput
End If
End If
(上面继续进行操作以允许搜索更多文件)...
Sub cleanCSV()
'removes rows in csv files where the entered email is found
Dim Cell As Variant
Dim SrchRng As Range
Set SrchRng = ActiveSheet.UsedRange
lastIndex = SrchRng.Rows.Count
For i = lastIndex To 1 Step -1
For Each Cell In SrchRng.Rows(i).Cells
If Cell.Value = SrchStr Then
Debug.Print
Cell.EntireRow.Delete
Exit For
End If
Next
Next
ActiveWorkbook.Close SaveChanges:=True
End Sub
Sub cleanTXT()
Dim str As String
'removes lines in text files where the entered email is found
Const myOutput As String = "G:\Team Drives\Technology Team\Data Management\Admin\GDPR\tempoutput.txt"
Open myOutput For Output As #2
Do Until VBA.EOF(1)
Line Input #1, str
If InStr(1, str, SrchStr) = 0 Then
Print #2, str
End If
Loop
End Sub
任何帮助或指导将不胜感激!
谢谢。
答案 0 :(得分:0)
您在不同的子例程中执行同一过程的不同部分,并且依靠activeworkbook是正确的例程,因此也难怪它获取了错误的文件。将您的主要代码切换到表单中
If File1 <> "" Then
If Right$(File1, 3) = "csv" Then
CleanCsv File1
Else
cleanTXT File1
End If
End If
现在将其余所有代码放入两个子例程中:
Sub CleanCSV(filetoclean as string)
Dim wb as workbook
set wb = Workbooks.open(filetoclean)
Dim Cell As Variant
Dim SrchRng As Range
Set SrchRng = wb.sheets(1).UsedRange
'etc....
wb.close
end sub
和
Sub CleanTxt(filetoclean as string)
Open Filetoclean For Input As #1
Dim myOutput As String:
myOutput = "G:\Team Drives\Technology Team\Data Management\Admin\GDPR\tempoutput.txt"
etc...
一般来说,文件应该由打开该文件的例程关闭,并且应该始终将指向工作簿的指针作为参数进行传递-不要依赖activeworkbook仍然是您要在调用例程时想要的文件