![如何根據Excel中的符合條件取得儲存格值?](https://rvso.com/image/1518622/%E5%A6%82%E4%BD%95%E6%A0%B9%E6%93%9AExcel%E4%B8%AD%E7%9A%84%E7%AC%A6%E5%90%88%E6%A2%9D%E4%BB%B6%E5%8F%96%E5%BE%97%E5%84%B2%E5%AD%98%E6%A0%BC%E5%80%BC%EF%BC%9F.png)
如圖所示,我在 Excel 文件中有 AC 欄位。我的問題是創建一個類似於 EG 列中給出的表。我怎麼能在Excel中做到這一點?
答案1
下面的巨集產生的輸出形狀如所附影像所示。
'assumptions
'(1) the input data is in columns A,B,C
'(2) the output data is rendered in columns E,F,G
Sub ListByTeacher()
Dim noOfRows As Integer
Dim i As Integer
Dim j As Integer
Dim c_lv_array(1) As String ' c - course, lv - load value
Dim c As New Collection 'output table with values
Dim k As New Collection 'keys
Dim tmpVar As Variant
'[INPUT]
'identify no of rows with data
i = 1
Do While Len(Cells(i, 1).Value) > 0
i = i + 1
Loop
noOfRows = i - 1
'Loop through input data rows and build the collection of teachers
For i = 2 To noOfRows
c_lv_array(0) = Trim(CStr(Cells(i, 1).Value))
c_lv_array(1) = Trim(CStr(Cells(i, 2).Value))
On Error Resume Next
tmpVar = c.Item(Trim(CStr(Cells(i, 3).Value))) 'if teacher in collection
If IsArray(tmpVar) = True Then 'exists
If InStr(1, tmpVar(0), c_lv_array(0), vbBinaryCompare) = 0 Then
'c_lv_array(0) = c_lv_array(0) & ", " & tmpVar(0) 'use this line or below one
c_lv_array(0) = tmpVar(0) & ", " & c_lv_array(0) 'reversed order to the above line
c_lv_array(1) = CStr(CInt(c_lv_array(1)) + CInt(tmpVar(1)))
End If
c.Remove Trim(CStr(Cells(i, 3).Value))
c.Add Item:=c_lv_array, Key:=Trim(CStr(Cells(i, 3).Value))
End If
tmpVar = Empty
c.Add Item:=c_lv_array, Key:=Trim(CStr(Cells(i, 3).Value))
k.Add Item:=Trim(CStr(Cells(i, 3).Value)), Key:=Trim(CStr(Cells(i, 3).Value))
Next i
'[OUTPUT]
'Render the result in s/s
Cells(1, 5) = "Teacher"
Cells(1, 6) = "Courses"
Cells(1, 7) = "Load"
j = 2
For i = 1 To c.Count
tmpVar = c.Item(k.Item(i))
Cells(j, 5) = k.Item(i)
Cells(j, 6) = tmpVar(0)
Cells(j, 7) = tmpVar(1)
j = j + 1
Next i
End Sub
答案2
您確實應該為此製作一個資料透視表。
這樣,您將能夠新增到 AC 列中的列表,同時不斷更新 EG 中的其他觀點。
但它確實需要兩件事:
- 為了能夠不斷更新資料透視表中的值,列 A 到 C 應該變成一個表 (
CTRL + L
)。 - 資料透視表有它自己的工作表。