2017-08-09 22 views
0

我發現了相當多的數據拆分VBA代碼帖子,但沒有按內容拆分它並拉入標題並將結果放入新工作表(我需要將原始數據保留在原始狀態)。將單行數據分割成多個獨特的行到一個新工作表中,以包含作爲值和單元格內容的標題作爲值

我有一個電子表格,其中包含國家作爲標題的列中的值,我需要將每行分割成新工作表中的新行,並在新列中列出國家和來自同一國家/地區列中的值新的一排。

我想忽略任何國家頭,其中單元的內容是空白的,如與行的例子3.

這是原始數據的一個小例子: Raw Data Example

,這就是我需要3行變成: Required Results

雖然我問VBA代碼,我還不知道怎麼寫VBA,只調整,我已經在互聯網上找到適合我的場景代碼。

回答

0

既然你是新的編碼VBA,我用For和If做了一個簡單的代碼,試着學習這個函數。 我沒有聲明每個變量,嘗試聲明它們並瞭解數據類型。 LAST_ROW LAST_COLUMN和是變量,可以幫助很多在Excel VBA中,主要是爲了使動態電子表格

Sub test() 
'Declare variables here 
Dim sht1, sht2 As Worksheet 

'sht1 has the data and sht2 is the output Worksheet, you can change the names 
Set sht1 = ThisWorkbook.Worksheets("Sheet1") 
Set sht2 = ThisWorkbook.Worksheets("Sheet2") 

last_row1 = sht1.Range("A65536").End(xlUp).Row 
last_column = sht1.Cells(1, sht1.Columns.Count).End(xlToLeft).Column 
x = 1 

'Add header 
sht2.Cells(1, 1) = "Company" 
sht2.Cells(1, 2) = "Country" 
sht2.Cells(1, 3) = "Status" 
'Data add 
For i = 2 To last_row1 
'Assuming Company is in Column 1 or A 
    For k = 2 To last_column 
     'If cell is different from blank then write data 
     If sht1.Cells(i, k) <> "" Then 
     sht2.Cells(x + 1, 1) = sht1.Cells(i, 1) 
     sht2.Cells(x + 1, 2) = sht1.Cells(1, k) 
     sht2.Cells(x + 1, 3) = sht1.Cells(i, k) 
     x = x + 1 
     End If 
    Next k 
Next i 

MsgBox "Data Updated" 
End Sub 

下一次,嘗試學習一些編碼和發佈您的代碼。

+0

我通常會自己做一些工作,但在這種情況下,我真的很努力地找到任何接近我想要實現的東西。下次我會更努力。這工作非常好,非常感謝。我已標記爲正確的答案。 –

相關問題