2016-02-09 32 views
0

我在VBA中有一个If/Then循环,用于检查每个选项卡中的相同单元格是否相等,并且可以创建一个可在If/Then循环中工作的字符串给定已知数量的选项卡(3个选项卡);但是,宏需要查看任意数量的选项卡,我需要一个动态的If/Then语句。我试图创建一个字符串,基本上根据选项卡的数量编写代码,但是我得到类型不匹配,因为字符串是一个变量。使用字符串作为If语句(VBA)的一部分

例如,这个工程给予3个标签:

If Worksheets(loc(1)).Cells(TseriesLine, 15) = Worksheets(loc(2)).Cells(TseriesLine, 15) _ 
    And Worksheets(loc(1)).Cells(TseriesLine, 15) = Worksheets(loc(3)).Cells(TseriesLine, 15) Then 

....

但是,这并不工作:

ifline = "Worksheets(loc(1)).Cells(TseriesLine, 15) = Worksheets(loc(2)).Cells(TseriesLine, 15) _ 
    And Worksheets(loc(1)).Cells(TseriesLine, 15) = Worksheets(loc(3)).Cells(TseriesLine, 15)" 

If ifline Then .... 

我使用Evalulate(ifline)也尝试和StrConv(ifline)没有成功。任何帮助,将不胜感激。

谢谢

+0

这是一个可怕的做法,但在这里你去http://simeonpilgrim.com/blog/2007/12/04/compiling-and-running-code-at-runtime/发表您的代码,我们可以帮助您到达那里 – Claudius

+0

使用'For Each'循环遍历表单。并将每张纸与第一张纸进行比较。如果有的话是不真实的,那么不要做其余的事情。然后根据结果分配一个布尔变量true或false。然后您可以测试该布尔变量。 –

回答

1

尝试类似这样的东西。

如果您知道您不想检查的工作表,您可以轻松测试其他工作表名称。

Dim sValue As String 
Dim ws1 As Worksheet 
Set ws1 = Worksheets("loc(1)") 

sValue = ws1.Cells(TseriesLine, 15).Value2 

Dim bifline As Boolean 
bifline = True 

Dim ws As Worksheet 
For Each ws In ThisWorkbook.Worksheets 

    If ws.Name <> ws1.Name Then 
     If sValue <> ws.Cells(TseriesLine, 15).Value2 Then 
      bifline = False 
      Exit For 
     End 
    End If 

Next 

If bifline Then 
    'more code 
End If 
1

您可以在每张工作表集合中的每个工作簿对象中循环显示每张工作表。

Function doesRangeMatch(rangeAddress As String) As Boolean 
    Dim ws As Worksheet 

    For Each ws In ThisWorkbook.Worksheets 
     If ThisWorkbook.Worksheets(1).Range(rangeAddress).Value <> ws.Range(rangeAddress).Value Then 
      doesRangeMatch = False 
      Exit Function 'early exit if match not found 
     End If 
    Next 
    doesRangeMatch = True 'if loop goes through then all must match 
End Function 
0

非常感谢大家!我用了一些建议组合来提出循环。这里是解决方案:

For ss = 2 To numloc 
    If Worksheets(loc(1)).Cells(TseriesLine, 15) <> Worksheets(loc(ss)).Cells(TseriesLine, 15) Then 
     doNumMatch = False 
Exit For 
    Else: doNumMatch = True 
    End If 
Next 

If doNumMatch Then 
相关问题