作者BanPeeBan (踢屁屁)
看板Visual_Basic
标题[VBA ] if函数判断错误?
时间Tue Nov 27 20:02:49 2018
各位大大好
延续上次的问题
(文章代码:
#1RzhUY6f )
这次需要"先判断工作表是否存在"
如果存在,则跳过(即继续执行回圈)
如果不存在,则新增该工作表
不知道是不是因为使用了 On Error Resume Next
导致全部皆判定为"工作表存在",以至於无法新增@@
请问这该怎麽解决?
------------------------------我是程式码------------------------------
Sub skip_sheet()
mydir = ActiveWorkbook.Path
abook = ActiveWorkbook.Name
asheet = ActiveSheet.Name
Set fs = Application.FileSearch
With fs
.LookIn = mydir
.Filename = "*.lod"
If .Execute(msoSortByFileName) Then
Nfile = .FoundFiles.Count
End If
MsgBox ("Nfile = " & Nfile)
s = ""
For i = 1 To Nfile
s = s & .FoundFiles(i) & Chr(10)
Next i
MsgBox (s)
sheetname = ""
For i = 1 To Nfile
Workbooks.OpenText Filename:=.FoundFiles(i),
DataType:=xlDelimited, Tab:=True, comma:=True, Space:=True
actb = ActiveWorkbook.Name
acts = ActiveSheet.Name
Workbooks(actb).Sheets(acts).Activate
sheetname = Right(.FoundFiles(i), 10)
sheetname = Left(sheetname, 6)
Range("A1").Select
Selection.Copy
Workbooks(abook).Activate
On Error Resume Next
Set ws = Sheets(sheetname)
If ws Is Nothing Then
MsgBox ("New Sheet! " & .FoundFiles(i))
Sheets.Add.Name = sheetname
'MsgBox ("Sheet " & sheetname & " Added")
Workbooks(abook).Sheets(sheetname).Activate
Range("A1").Select
ActiveSheet.Paste
Else
MsgBox ("Old Sheet! " & .FoundFiles(i))
Workbooks(abook).Sheets(asheet).Activate
Range("A1").Select
End If
Workbooks(actb).Activate
Application.CutCopyMode = False
Workbooks(actb).Close
Next i
End With
End Sub
------------------------------我是参考图片------------------------------
https://imgur.com/QAHflPp
https://imgur.com/HBufdcA
https://imgur.com/bu1OGcc
https://imgur.com/3EtLUMQ
https://imgur.com/hOD798N
https://imgur.com/AY4wxy0
https://imgur.com/Elv35kb
--
※ 发信站: 批踢踢实业坊(ptt.cc), 来自: 123.110.47.249
※ 文章网址: https://webptt.com/cn.aspx?n=bbs/Visual_Basic/M.1543320171.A.175.html
1F:→ newacc: 因为set ws那行跳错误,所以ws代表的物件没有被改变 11/28 23:46
2F:→ newacc: 试试看在前面加一行Set ws = Nothing 11/28 23:46
3F:推 newacc: 另外也可以考虑把"检查工作表是否存在"写成一个function 11/28 23:51
4F:→ newacc: 要传回布林值或该工作表都可以,这样好处是error handler 11/28 23:52
5F:→ newacc: 不会互相干扰,整个程式流程看起来会比较顺 11/28 23:52