2016-03-22 25 views
1

我有一個表是這樣的:VBA:獲取表格的標題和內容,並顯示輸出到文件

  Name Color Shape Size Cost Note 1 Note 2 
Ctrl But A Fruit 1 a  d  f  1  6  9 
Ctrl But B Fruit 2 b  e  g  2  7 
Ctrl But C Fruit 3 a  d  f  3  10 
Ctrl But D Fruit 4 b  e  g  4  8 

其中「按Ctrl但A」是控制按鈕。

當每個按鈕被按下時,我想輸出特定格式的行信息到csv文件中。例如,如果按下按鈕A我想輸出如下:

Name: Fruit A 
Colour: a 
Shape: d 
Size: f 
Cost: 1 
Note 1: 6 
Note 2: 9 

什麼是實現這一目標的最佳途徑,如果表中的列是可變的?

的代碼會做這樣的事情:

1. go to the top of the 'Name' cell 
2. look up the value in the same row as the button 
3. go to the top of the 'Color' cell 
4. look up the value in the same row as the button 
repeat until the end of the row is reached 
output and save file 

你的幫助是極大的讚賞!

回答

1

假設:

  • 細胞基本按鍵是空
  • 列數據開始的按鈕右側

的你可以試試這個

Option Explicit 

Sub FruitButton() 
Dim iRow As Long, iniCol As Long, endCol As Long, jCol As Long 

Open "C:\mypath\myfile.csv" For Output As #1 '<== adapt it to your needs 

With ActiveSheet 
    Call GetIniEndCol(.Buttons(Application.Caller), ActiveSheet, iRow, iniCol, endCol) 
    For jCol = iniCol To endCol 
     Write #1, .Cells(1, jCol) & ": " & .Cells(iRow, jCol) 
    Next jCol 
End With 

Close #1 

End Sub 


Sub GetIniEndCol(myButton As Button, ws As Worksheet, iRow As Long, iniCol As Long, endCol As Long) 
Dim iCol As Long 

With myButton.TopLeftCell 
    iRow = .Row 
    iCol = .Column 
End With 

With ws 
    iniCol = .Cells(iRow, iCol).End(xlToRight).Column 
    endCol = .Cells(iRow, .Columns.Count).End(xlToLeft).Column 
End With 

End Sub 
相關問題