我在excel的宏中有一个代码。在Sheet4
并且在我的代码的一部分中:
Call functionA("file.csv", "A3", "Sheet2")
我需要,如果宏不能执行隐藏列的功能
我打算使用以下代码,但不能正常工作
On Error Resume Next
all functionA("file.csv", "A3", "Sheet2")
Columns("Sheet3!V:V").EntireColumn.Hidden = True
首先永远不要隐藏特定工作表的列。 如果有错误继续,它工作正常。问题是我意图隐藏列。我只有在出现错误时才需要隐藏列
问题是我读了一些csv文件。 functionA将文件加载到excel。如果文件不存在excel必须继续并隐藏Sheet 3的第V列,因为在Sheet 3的V中我有一些日期,我计算的文件不存在
答案 0 :(得分:1)
How to Use "On Error" to Handle Errors in a Macro怎么样?您可以查看good-patterns-for-vba-error-handling我经常use the macro recorder来记录它时我不知道的内容,然后查看生成的宏代码。
Sub MyMacro()
On Error GoTo ErrorHandler
. . .
Exit Sub
ErrorHandler:
. . .
Resume <or Exit Sub>
. . .
End Sub
Sub HideColumn()
Dim colIndex As Integer
colIndex = CInt(InputBox("Index of column to hide"))
Cells(1, colIndex).EntireColumn.Hidden = True
End Sub
答案 1 :(得分:1)
好的,我在这里做了一些假设,但这应该让你走上正确的道路:
Option Explicit
Sub a()
If FileThere("c:\test\file.csv") Then
Call functionA("file.csv", "A3", "Sheet2")
{WHATEVER ELSE NEEDS TO HAPPEN AFTER THAT functionA CALL GOES HERE}
Else
Sheet3.Range("V:V").EntireColumn.Hidden = True
Exit Sub
End If
End Sub
Function FileThere(FileName As String) As Boolean
If (Dir(FileName) = "") Then
FileThere = False
Else:
FileThere = True
End If
End Function
Sub functionA(f1 As String, f2 As String, f3 As String)
{WHATEVER YOU NEED TO DO GOES HERE}
End Sub
答案 2 :(得分:0)
让您的函数返回成功值。
所以:这是你的功能
Function functionA (Byval Cvsfiel As string, byVal SheetName as string) as integer
On error go to Err
' insert your code here
....
...
....
return 0 '0 means function was successfull
Exit function
Err:
Return -1 ' -1 means function did not run successfullt
End Function
现在您的代码将是:
Dim result as integer
result=functionA("file.csv", "A3", "Sheet2")
If result=-1 then 'means if error
Columns("Sheet3!V:V").EntireColumn.Hidden = True
End If