关于excel:如何使用VBA中的单个按钮从不同的工作表中获取内容?

How to fetch contents from different worksheets using a single button in VBA?

我是VBA excel中的新手。我想在一个工作表中创建一个按钮,然后处理以将所有工作表表的行值打印到一个文件中。我有3个名为" sheet1"," sheet2"," sheet3"的工作表。按钮位于sheet1内部。现在,我已经编写了一些代码来处理该按钮。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
Sub Button_Click()
Dim fso As Object
Set fso = CreateObject("Scripting.FileSystemObject")
Dim Fileout As Object
Set Fileout = fso.CreateTextFile("myPath\\MyFile.txt", True, True)

Set ws = Sheets("sheet2")
Set sh = Sheets("sheet3")

/* I want to print sheet2 table row values to file */

Fileout.Write"print each row to file"

/* I want to get sheet3 table row values to file */

Fileout.Write"print each row to file"

Fileout.Close

End Sub

我想知道如何一张一张地遍历表格表行。有什么帮助吗?或建议?


您可以使用如下所示的for...each循环。

1
2
3
4
5
6
7
8
dim sh as worksheet, r as row
for each sh in thisworkbook.worksheets
    if sh.name = sh.name ="sheet2" or sh.name ="sheet3" then
        for each r in sh.cells.usedrange.rows
            fileout.write r.value
        next r
    end if
next sh