2013-10-15 110 views
0

所以我想用Excel創建一個報表模板。截至目前,我們從我們的數據庫中提取數據並手動將其輸入到我們的模板中。基於來自一個封閉的Excel工作簿Sheet1的值的單元格

我想要做的是創建一個VBA代碼,將查找填充數據導出的封閉Excel文件(TEST.XLS)(例如,在單元格B1:B21)。

在單元B1中的數據:B21具有每行之間的空間。所以垂直列會像以下(Data1,空間,空間,Data2 ....)

我想這個例外的空間,然後將其放入報告Excel文件,並水平移動(A10「 Data1「,B10」Data2「,C10」data3「...)而不是垂直。

我有VBA的一個基本的瞭解(我通常是谷歌和peice的代碼放在一起得到的東西做,因爲我想,但是這一次似乎有點複雜,然後我使用)。這樣做的目標也是減少輸入/複製數據的時間。

至於直接從數據庫到Excel模板把數據的選擇,我們不能這樣做,因爲安全的原因。

編輯:

解決方案如下圖:再次

Private Function GetValue(path, file, sheet, ref, v) 

path = "C:\Documents and Settings\sdavis\Desktop\Index\XXX\Results" 
file = "test.xls" 
sheet = "Sheet1" 
ref = "A1:R30" 



' Retrieves a value from a closed workbook 
Dim arg As String 
Dim p As Integer 
' Make sure the file exists 
If Right(path, 1) <> "\" Then path = path & "\" 
If Dir(path & file) = "" Then 
    GetValue = "File Not Found" 
    Exit Function 
End If 








' Create the argument 
arg = "'" & path & "[" & file & "]" & sheet & "'!" & _ 
Range(ref).Cells(v, 2).Address(, , xlR1C1) 



' Execute an XLM macro 
GetValue = ExecuteExcel4Macro(arg) 


End Function 

Sub TestGetValue() 

'Declare 
Dim v As Integer 

'Starting Point 
v = 21 

'File Location 
path = "C:\Documents and Settings\sdavis\Desktop\Index\XXX\Results" 
file = "test" 
sheet = "Sheet1" 

Application.ScreenUpdating = False 


    For C = 1 To 15 

     a = Cells(5, C).Address 
     Cells(5, C) = GetValue(path, file, sheet, a, v) 
     v = v + 3 
    Next C 


Application.ScreenUpdating = True 
End Sub 

謝謝, 亞歷克斯

+0

我相信你需要打開XLS實際上從它讀,但如果在vba中完成,excel實例可以隱藏,即不會向用戶顯示另一個excel文件正在打開。 – Jaycal

+0

具有在外表[**'here' **](http://stackoverflow.com/questions/18481330/2-dimensional-array-vba-from-cell-contents-in-excel/18481730#18481730)和學習一下關於「移調」功能:) – 2013-10-15 14:40:54

+0

打開文件,將列複製/粘貼到新工作表,過濾掉空白,複製/粘貼特殊轉置。 –

回答

0
Private Function GetValue(path, file, sheet, ref, v) 

path = "C:\Documents and Settings\sdavis\Desktop\Index\XXX\Results" 
file = "test.xls" 
sheet = "Sheet1" 
ref = "A1:R30" 



' Retrieves a value from a closed workbook 
Dim arg As String 
Dim p As Integer 
' Make sure the file exists 
If Right(path, 1) <> "\" Then path = path & "\" 
If Dir(path & file) = "" Then 
    GetValue = "File Not Found" 
    Exit Function 
End If 








' Create the argument 
arg = "'" & path & "[" & file & "]" & sheet & "'!" & _ 
Range(ref).Cells(v, 2).Address(, , xlR1C1) 



    ' Execute an XLM macro 
GetValue = ExecuteExcel4Macro(arg) 


End Function 

Sub TestGetValue() 

'Declare 
Dim v As Integer 

'Starting Point 
v = 21 

'File Location 
path = "C:\Documents and Settings\sdavis\Desktop\Index\XXX\Results" 
file = "test" 
sheet = "Sheet1" 

    Application.ScreenUpdating = False 


    For C = 1 To 15 

     a = Cells(5, C).Address 
     Cells(5, C) = GetValue(path, file, sheet, a, v) 
     v = v + 3 
    Next C 


Application.ScreenUpdating = True 
End Sub 
相關問題