![](/img/trans.png)
[英]If a cell's value is found on another column, how to return the cell's value from another column which is on same row with the synced cell?
[英]How to get VBA code to check if cell value matches column heading and return value from another cell in the same row?
我已經搜索了所有內容,似乎無法正常運行。
我有2個工作表。
表格1包含測驗問題編號,然后是每個相應q#的分數。
第2頁包含每個q#作為列標題,我希望VBA代碼從與正確標題對應的q#中獲取分數。
例如:
工作表1
Question# Score
1 100
2 90
3 75
4 95
工作表2
Q1 Q2 Q3 Q4
100 90 75 95
可以將工作表2中的列標題更改為簡單地說“ 1”,“ 2”等,這樣可以使精確匹配變得更容易。
我發現並使用此代碼,但是如果找到不起作用的匹配項,它將復制整列:
Sub CopyDataDynamically()
Dim lr As Long, num As Long
Dim rng As Range
lr = Cells(Rows.Count, 1).End(xlUp).Row
Set rng = Range("a2")
num = Range("b2").Value
If num = 1 Then
Range("B2:B" & lr).Copy
rng.Offset(0, num - 1).PasteSpecial xlPasteValues
End If
End Sub
提前致謝!
我總是覺得對Workbook
和Worksheet
進行調Dim
是一種很好的做法。 如果您決定擴大規模,那么您已經設置好了。
不管有多少問題,以下代碼都會從本質上轉置數據集。
Sub test()
Dim wbk As Workbook
Dim wks_1 As Worksheet
Dim wks_2 As Worksheet
Set wbk = ThisWorkbook
Set wks_1 = wbk.Sheets("Sheet1")
Set wks_2 = wbk.Sheets("Sheet2")
LastRow = wks_1.Range("A" & Rows.Count).End(xlUp).Row
For i = 1 To LastRow
wks_1.Cells(i, 1).Copy wks_2.Cells(1, i)
wks_1.Cells(i, 2).Copy wks_2.Cells(2, i)
Next i
End Sub
它還將復制標題。
首先,我想知道最后一行在哪里,因此想知道LastRow
代碼。 然后,我們簡單地遍歷所有行並轉置數據集。
參考.Cells
管線wks_1.Cells(i, 1).Copy wks_2.Cells(1, i)
始終引用Row
然后Col
。
讓我知道你怎么去。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.