您好我目前在Excel文件的“值”标签中提取了数字。但是如果Tab2存在于该文件中,我想从Tab2中提取它。如果Tab2存在,可以在某处建议如何做某事,先使用Tab2,否则使用Value选项卡?
Workbooks(wkbk_value).Sheets("Value").Select
amount= WorksheetFunction.Match("Date", Rows("5:5"), 0)
price = WorksheetFunction.Match("Calculated", Rows("4:4"), 0)
time= WorksheetFunction.Match("Selected", Rows("3:3"), 0)
答案 0 :(得分:0)
备注:强>
Option Explicit
放在代码的顶部,并确保声明所有变量。例如,wkbk_value
在哪里声明并分配?.Select
并使用With
语句处理工作表Worksheets
集合而不是表格。代码:
的方法Option Explicit
Public Sub test()
Dim amount As Variant, Price As Variant, Time As Variant, wkbk_value As String '<== Declare your variables with appropriate type
wkbk_value = "Testing.xlsb"
If SheetExists("Tab2", Workbooks(wkbk_value)) Then
'Code here for Tab2
MsgBox "EXISTS"
Else
With Workbooks(wkbk_value).Worksheets("Value") '<==use With statement not .Select
'Consider how to handle not being found?
amount = Application.Match("Date", .Rows("5:5"), 0)
Price = Application.Match("Calculated", .Rows("4:4"), 0)
Time = Application.Match("Selected", .Rows("3:3"), 0)
End With
End If
End Sub
Public Function SheetExists(ByVal shtName As String, Optional ByRef wb As Workbook) As Boolean
Dim sht As Worksheet
If wb Is Nothing Then Set wb = ThisWorkbook
On Error Resume Next
Set sht = wb.Sheets(shtName)
On Error GoTo 0
SheetExists = Not sht Is Nothing
End Function
答案 1 :(得分:0)
您可以尝试下面的内容。
我已将变量声明为variant并使用Application更改了WorksheetFunction,以便在未找到查找值时,变量将保留错误编号,以便您可以检查Match函数是否返回值或错误(如果需要)。
Dim ws As Worksheet
Dim Amount, Price, Time
On Error Resume Next
Set ws = Workbooks(wkbk_value).Sheets("Tab2")
On Error GoTo 0
If ws Is Nothing Then Set ws = Workbooks(wkbk_value).Sheets("Value")
With ws
Amount = Application.Match("Date", .Rows("5:5"), 0)
Price = Application.Match("Calculated", .Rows("4:4"), 0)
Time = Application.Match("Selected", .Rows("3:3"), 0)
End With
End Sub
您编辑的代码:
Dim ws As Worksheet
Dim Amount, Price, Time
On Error Resume Next
Set ws = Workbooks(wkbk_value).Sheets("Tab2")
Amount = Application.Match("Date", ws.Rows("5:5"), 0)
On Error GoTo 0
If ws Is Nothing Then
Set ws = Workbooks(wkbk_value).Sheets("Value")
Amount = Application.Match("Date", ws.Rows("5:5"), 0)
End If
请注意,在您的代码中,您有两行计算金额,就像您首先集中设置工作表(ws)一样,您只需要编写该行一次,它将根据之前设置的工作表正确计算如第一段代码所示。