如果tab1存在则使用tab1,否则使用tab2

时间:2018-06-05 19:01:57

标签: excel vba excel-vba

您好我目前在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)

2 个答案:

答案 0 :(得分:0)

备注:

  1. Option Explicit放在代码的顶部,并确保声明所有变量。例如,wkbk_value在哪里声明并分配?
  2. 避免使用.Select并使用With语句处理工作表
  3. 考虑为通过声明变体找不到的匹配项添加错误处理,然后针对错误值测试这些匹配项的值
  4. 除非希望包含图表,否则一般使用Worksheets集合而不是表格。
  5. 匹配,如果找到,将返回一个数字(在范围内找到的位置)。它看起来更像是你想要返回一个值,所以要注意这一点。
  6. 代码:

    使用@TimWilliams

    的方法
    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)一样,您只需要编写该行一次,它将根据之前设置的工作表正确计算如第一段代码所示。