[英]Use a string as part of an If statement (VBA)
我在VBA中有一個If / Then循環,它檢查每個選項卡中的相同單元格是否相等,並且我可以創建一個字符串,該字符串在給定已知數量的選項卡(3個選項卡)的情況下在If / Then循環中起作用; 但是,宏需要查看任意數量的選項卡,並且我需要動態的If / Then語句。 我試圖創建一個字符串,該字符串本質上是基於選項卡的數量來編寫代碼的,但是由於字符串是一個變量,所以我得到了Type Mismatch。
例如,這在給定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)失敗。 任何幫助,將不勝感激。
謝謝
嘗試這樣的事情。
如果有您不想檢查的工作表,則可以輕松地針對其他工作表名稱進行測試。
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
您可以使用每個工作簿對象中的工作表集合在每個工作表上循環。
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
非常感謝大家! 我結合了一些建議來提出循環。 解決方法如下:
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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.