2014-09-30 83 views
0

我還是VBA EXCEL編程的新手。VBA爲不同格式的數據獲取新工作表Excel

我需要以不同格式從一張表格提取數據到另一張表格。但是,許多教程似乎只是按行提取數據行,或者按範圍將數據範圍提取到新的工作表。

所以這是我DataSheet1:

**School   Principal Student Student ID** 
United College Bill Gates Peter  p3214 
United College Bill Gates Mary  p4213 
United College Bill Gates Forge  p7621 
Beverly High  Melin Brad Goge  p1111 
Beverly High  Melin Brad Fred  p2222 

我想使數據到另一個數據表自定義格式。因此,這裏是我想要的結果:

School  United College 
Principal Bill Gates 

Student Student ID 
Peter  p3214 
Mary  p4213 
Forge  p7621 


School  Beverly High 
Principal Melinda Brad 

Student Student ID 
Goge  p1111 
Fred  p2222 

下面是我的一些代碼,以獲得工作表Sheet1到Sheet2,但代碼只顯示擺脫範圍內的數據範圍。應該用於將數據提取到自定義格式中的一些概念是什麼?我的代碼:

Dim secondsheet As Worksheet 
Set secondsheet = workbook.Worksheets(2) 
Dim firstsheet As Worksheet 
Set firstsheet = workbook.Worksheets(1) 

secondsheet.Range("A1", "C10").Value = firstsheet.Range("A1", "C10").Value 

,格式,我打算把我的數據:

Range(<<call function for range>>).Select 
With Selection 
    .Value = "School" 
    .Offset(1,0).Value = "Principal" 
    .Offset(1,0).Font.Bold = True 
    .Offset(4,1).Value = "Student" 
    .Offset(4,1).Font.Bold = True 
    .Offset(4,2).Value = "Student ID" 
    .Offset(4,2).Font.Bold = True 

所以我要找的是循環的功能,因爲它是在這種格式的答案。任何一種靈魂都願意幫助我理解vba的概念嗎?

回答

0

保留數據在Sheet1並運行宏...小錯誤就在我的宏..如果妳解決它可以很容易地糾正

col1 = Sheet1.Cells(2, 1) 
prin1 = Sheet1.Cells(2, 2) 
Sheet2.Cells(1, 1) = "School" 
Sheet2.Cells(1, 2) = "Principal" 
Sheet2.Cells(2, 1) = col1 
Sheet2.Cells(2, 2) = prin1 
b = 5 
c = 1 
Sheet2.Cells(b - 1, 1) = "Student" 
Sheet2.Cells(b - 1, 2) = "St ID" 
a = 3 

Do While Sheet1.Cells(a, 1) <> "" 
If col1 = Sheet2.Cells(c + 1, 1) Then 
Sheet2.Cells(b, 1) = Sheet1.Cells(a, 3) 
Sheet2.Cells(b, 2) = Sheet1.Cells(a, 4) 
b = b + 1 
Else 
c = b + 1 
b = c + 3 

col1 = Sheet1.Cells(a, 1) 
prin1 = Sheet1.Cells(a, 2) 
Sheet2.Cells(c, 1) = "School" 
Sheet2.Cells(c, 2) = "Principal" 
Sheet2.Cells(c + 1, 1) = col1 
Sheet2.Cells(c + 1, 2) = prin1 
Sheet2.Cells(b - 1, 1) = "Student" 
Sheet2.Cells(b - 1, 2) = "St ID" 
Sheet2.Cells(b, 1) = Sheet1.Cells(a, 3) 
Sheet2.Cells(b, 2) = Sheet1.Cells(a, 4) 
End If 
a = a + 1 
Loop 
+0

我試圖提取的數據是不完全一樣示例中顯示了什麼。沒有來自類似學校的學生的匹配?這太奇怪了。 – 2014-09-30 07:33:44

相關問題