如何从2个不同的工作表中匹配相同的名称后获取%值

时间:2012-02-23 03:41:29

标签: excel vba excel-vba

我想知道是否有人可以帮我解决以下问题。之前有人曾帮助我在同一工作表上获得 dctest / In 值的百分比。但是现在,我需要在不同的工作表上做同样的事情。

说Sheet1

enter image description here

在获取%

后复制Sheet1(1)

enter image description here

Sub marco1()

'start making Sheet1 into %
'~~> Add/Remove the text here which you want to ignore
Excludetext = "In,test1,test2,test3,test4,test5,test6"

MyArray = Split(Excludetext, ",")

Set ws = Sheets("Sheet1")
LastRow = ws.Range("A" & Rows.Count).End(xlUp).Row

'Set Column B into %
For i = 1 To LastRow
    boolContinue = True

    For j = 0 To UBound(MyArray)
        SearchText = UCase(Trim(MyArray(j)))
        If UCase(Trim(ws.Range("A" & i).Value)) = SearchText Then
            boolContinue = False
            Exit For
        End If
    Next j

    If boolContinue = True Then
        With Range("B" & i)
            .Formula = _
            "=OFFSET(INDIRECT(ADDRESS(INDEX(MATCH(A" & i & _
            ",$A$1:$A$45,0),1,0),1,1,1,'Duplicated_Sheet1')),0,1)/$B$5"
            .NumberFormat = "0.00%"
        End With
    End If
Next i
End sub

在公式中显示有一些错误,我是否在公式中犯了错误?提前谢谢!

1 个答案:

答案 0 :(得分:1)

这是你在尝试的吗?

已经过测试

Option Explicit

Sub Sample()
    Dim ws As Worksheet
    Dim wsData As String
    Dim SearchText As String, Excludetext As String
    Dim LastRow As Long, i As Long, j As Long
    Dim MyArray() As String
    Dim boolContinue As Boolean

    '~~> Add/Remove the text here
    Excludetext = "In,Test1,Test2,Test3,Test4,Test5,Test6"

    '~~> Change this to the relevant sheetname which has the data
    wsData = "Sheet1"

    MyArray = Split(Excludetext, ",")

    Set ws = Sheets("Sheet2")
    LastRow = ws.Range("A" & Rows.Count).End(xlUp).Row

    For i = 1 To LastRow
        boolContinue = True

        For j = 0 To UBound(MyArray)
            SearchText = MyArray(j)
            If ws.Range("A" & i).Value = SearchText Then
                boolContinue = False
                Exit For
            End If
        Next j

        If boolContinue = True Then
            With ws.Range("B" & i)
                .Formula = _
                "=OFFSET(INDIRECT(ADDRESS(INDEX(MATCH(A" & i & _
                "," & wsData & "!$A$1:$A$11,0),1,0),1,1,TRUE,""" & _
                wsData & """)),0,1)/" & wsData & "!B1"
                .NumberFormat = "0.00%"
            End With
        End If
    Next i
End Sub

对不同工作表中的单元格使用ADDRESS()时,必须指定其他参数。

直接来自Excel的帮助

ADDRESS函数的语法

ADDRESS(row_num, column_num, [abs_num], [a1], [sheet_text])

[sheet_text] 是我们所指的工作表的名称。我建议您在Excel帮助中阅读更多相关内容。

这是 dctest

的实际公式
=OFFSET(INDIRECT(ADDRESS(INDEX(MATCH(A7,Sheet1!$A$1:$A$11,0),1,0),1,1,TRUE,"Sheet1")),0,1)/Sheet1!B1

HTH

西特