Excel 从一个 table/array 到另一个选择值的宏

Excel Macro to pick values from one table/array to another

我在 Excel sheet 中有以下 "table"。我想做以下更改:

每次有一个"x"我想在另一个sheet上报第一行对应的值和第一列对应的值:

"Original Table"

    a1      a2      a3      a7      a8      a9
    main    main    main    main    main    main
u1  X       X        X
u2          X        X
u3                      
u4                      
u5  X           
u6                   X      

"Transformed Table":

  u1 a1
  u1 a2
  u1 a3
  u2 a2
  u2 a3
  u5 a1
  u6 a3 

你能告诉我执行此操作的 Excel 宏是什么吗?

提前致谢。

这假定 sheet(2) 存在(即不检查)。它将使用行和列 headers 填充 sheet(2),正如您在示例中给出的那样:

Sub ReportOnAllXs()
  Dim r As Integer, c As Integer, r2 As Integer
  r2 = 1
  With Sheets(1)
    For r = 3 To .Cells(.Rows.Count, "A").End(xlUp).row
      For c = 2 To .Cells(1, .Columns.Count).End(xlToLeft).Column
        If .Cells(r, c).Value = "X" Then
          Sheets(2).Cells(r2, 1).Value = .Cells(r, 1).Value
          Sheets(2).Cells(r2, 2).Value = .Cells(1, c).Value
          r2 = r2 + 1
        End If
      Next
    Next
  End With
End Sub

我还假设您希望在 sheet(2) 上的单独单元格中生成行值和列值。

我知道这是 Excel VBA 的问题,它不能用内置公式来完成。在 Google 表格中,您只能使用内置函数来实现此目的。当'a1'对B1,'u1'对A3时,只需一个公式就可以得到table。样本 sheet 是 here.

=transpose(
  split(
   concatenate(
    arrayformula(
     if(B3:G8="x", "u"&(row(B3:G8)-row($A)+1)&" a"&(column(B3:G8)-column($B)+1)&char(10), "")
    )
   ), char(10)
  )
 )