作者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/m.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