0

我想根据特定条件在 Excel 工作表中的单个单元格中输入多个值,例如如果工作簿中有多个工作表,那么如果任何以名称 TC 开头的工作表中包含颜色,那么我必须输入信息在 Excel 工作簿的自述部分中的另一个工作表。我的代码的问题在于它不显示包含颜色的唯一工作表......假设工作表“TC_1”和“TC_3”在任何单元格中包含颜色,然后将输出显示为“;TC_3;TC_3;TC_3;” 虽然这里的预期输出是“TC_1;TC_3”。

这里,是代码:

Sub ErrorInSheet()
    Dim Row
    Dim Names As String
    Names = ""

    For Row = 2 To tsheet.UsedRange.Rows.Count
        For Chkcol = 1 To tsheet.UsedRange.Columns.Count
            If tsheet.Cells(Row, Chkcol).Interior.ColorIndex = 3 Then
                Names = Names & ";" & tsheet.Name
            End If
        Next
    Next Row

    Sheets("Read Me").Cells(13, 5).Value = Names

End Sub

Sub iterateSheets()

    For Each sheet1t In Worksheets

       If InStr(1, sheet1t.Name, "TC") Then
           Set tsheet = sheet1t
           Call ErrorInSheet
       End If
    Next
End Sub
4

1 回答 1

2

我认为这对您有用-我对其进行了测试并为我工作。

Sub FindErrors()
    Dim sht As Worksheet, cl As Range, shtNames As String

    shtNames = vbNullString

    For Each sht In Worksheets
       If Left$(sht.Name, 2) = "TC" Then
            For Each cl In sht.UsedRange.Cells
                If cl.Interior.ColorIndex = 3 Then
                    shtNames = IIf(shtNames = vbNullString, sht.Name, shtNames & ";" & sht.Name)
                End If
            Next cl
       End If
    Next sht

    Worksheets("Read Me").Cells(13, 5) = shtNames
End Sub

笔记:

  1. 我已经明确声明了变量
  2. I am assuming all your sheets start with "TC" so I've used Left$ but you can use InStr if you like
  3. I've used the ternary IIF statement to stop you getting a leading ;
  4. I've put all the code in one Sub but you can split it out if you like
于 2012-12-09T16:12:40.390 回答