2016-05-20 80 views
0

我正在做一個Excel提取並有一些格式問題。所以基本上我正在做的是進入SQL SERVER並選擇一堆數據。然後我將它寫入Excel(在VB6應用程序中)。Excel提取vba

xlrow=6 
xlcol=1 
While Not g_RS3.EOF 
    For i = 0 To RCOUNT - 1 
     Cells(xlRow, xlCol).Value = g_RS3("School") 
     xlCol = xlCol + 1 
     Cells(xlRow, xlCol).Value = g_RS3("LastName") & " ," & g_RS3("FirstName") 
     xlCol = xlCol + 1 
     Cells(xlRow, xlCol).Value = g_RS3("Q01") 
     xlCol = xlCol + 1 
     Cells(xlRow, xlCol).Value = g_RS3("Q02") 
     xlCol = xlCol + 1 
     Cells(xlRow, xlCol).Value = g_RS3("Q03") 
     xlCol = xlCol + 1 
     Cells(xlRow, xlCol).Value = g_RS3("q04") 
     xlCol = xlCol + 1 
     Cells(xlRow, xlCol).Value = g_RS3("q05") 
     xlcol=1 
     xlrow=xlrow+1 
    next i 
wend 

因此,我將這些數據寫入Excel,一切都很好。但我在格式化方面遇到困難。

我想使字體= 9並將邊框放在單元格周圍。因爲這是動態的(我不知道會有多少條記錄,我試圖在寫入時將其格式化)。我試圖把這一行我每次做xlcol=xlcol+1時間後,所以我做這樣的事情:

xlcol=xlcol+1 
cells(xlrow, xlcol).font.size=9 

但是我有充分的行後要做到這一點,也與邊界。有沒有更簡單的方法來做到這一點?謝謝!

編輯:包括此代碼不會爲我做這項工作,它只給我左右邊界,而不是頂部和底部,因爲它走遍了整個範圍。此外,它只是改變了第一列的字體......「學校」

Dim rng As Range 

Set rng = Range(Cells(6, 1), Cells(xlRow, xlCol)) 
rng.Font.Size = 9 
rng.Borders(xlEdgeBottom).LineStyle = xlContinuous 
rng.Borders(xlEdgeTop).LineStyle = xlContinuous 
rng.Borders(xlEdgeRight).LineStyle = xlContinuous 
rng.Borders(xlEdgeLeft).LineStyle = xlContinuous 

我需要的東西

+1

爲什麼你不能在所有數據寫入後格式化? – findwindow

+0

因爲它是動態的,我不知道記錄集有多長,因此我不知道如何指定我的範圍 – FatBoySlim7

+0

這就是爲什麼你要等到它完成。然後你知道範圍是什麼。編輯:我錯過了什麼? – findwindow

回答

4

爲什麼不這樣的事情後的各行後,將寫在你的邊界循環:

Dim rng As Range 

Set rng = Range(Cells(6,1), Cells(xlrow, xlcol)) 

rng.font.size = 9 
rng.Borders.Color = RGB(0,0,0) 
rng.Borders(xlEdgeTop).Weight = xlThick 
etc... 
+0

我仍然會循環,不是嗎?只需設置xlrow,並且xlcol將不會遍歷所有行來格式化它 – FatBoySlim7

+1

是的,這會在循環之後執行。這樣xlrow和xlcol值應該對應於由循環處理的最後一個單元格,它使我們結束了範圍。 –

+0

請參閱編輯 – FatBoySlim7