我有一张这样的表:
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 But 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
非常感谢您的帮助!
答案 0 :(得分: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