VBA Print #1 选择范围(用于从 Excel 导出到文件)?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15125578/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
VBA Print #1 select range (for exporting from Excel to a file)?
提问by user2084296
I have a simple macro that exports desired cells to a txt-file. Can I instead of individually telling the macro what cells I want to export, choose a range of cells?
我有一个简单的宏,可以将所需的单元格导出到 txt 文件。我可以不单独告诉宏我要导出哪些单元格,而是选择一系列单元格吗?
Here's the very simple code I have:
这是我拥有的非常简单的代码:
Sub TEST()
Open "C:\text.txt" For Output As #1
Print #1, Cells(1, 1) & Cells(1, 2)
Close
End Sub
With that I can export Excel sheet cells A1, A2. But if I want to export wide range of cells, this method isn't too convenient. So is there a way I could, let's say easily export cells A1:A100?
有了它,我可以导出 Excel 工作表单元格 A1、A2。但是如果我想导出大范围的单元格,这种方法就不太方便了。那么有没有一种方法可以让我们说轻松导出单元格 A1:A100?
Thanks!
谢谢!
回答by mkingston
I see joseph4tw has already responded, but my answer is a little different and might give you another idea, so I'll put it here anyway.
我看到 joseph4tw 已经回复了,但我的回答有点不同,可能会给你另一个想法,所以我还是把它放在这里。
Sub TEST()
Dim c As Range, r As Range
Dim output As String
For Each r In Range("A1:C3").Rows
For Each c In r.Cells
output = output & c.Value & ","
Next c
output = output & vbNewLine
Next r
Open "H:\My Documents\text.txt" For Output As #1
Print #1, output
Close
End Sub
回答by Joseph
You can use the InputBox
and set the type to 8
, which will allow the user to click in Excel and select a range.
您可以使用InputBox
并将类型设置为8
,这将允许用户在 Excel 中单击并选择一个范围。
Here is an example:
下面是一个例子:
Sub test()
Dim r As Excel.Range, cell As Excel.Range
On Error Resume Next
Set r = Application.InputBox("Select Range", "Select Range", Type:=8)
On Error GoTo 0
If r Is Nothing Then Exit Sub
Open "C:\text.txt" For Output As #1
For Each cell In r
Print #1, cell.Value
Next
Close
End Sub
回答by billmanH
I notice that the example by mkingston puts the comma first. This would cause everything to start in the second column of the .csv (first column would be blank). A little better would be to put the comma at the end of the statement. You could remove the last ',' with REPLACE() but it isn't necessary.
我注意到 mkingston 的示例将逗号放在首位。这将导致所有内容从 .csv 的第二列开始(第一列将为空白)。将逗号放在语句末尾会更好一些。您可以使用 REPLACE() 删除最后一个 ',' ,但这不是必需的。
Dim c As range, r As range
Dim output As String
For Each r In range(DataRange).Rows
For Each c In r.Cells
output = output & c.Value & ","
Next c
output = output & vbNewLine
Next r
回答by runlevel0
If you want to select all non-empty cells (contigouos) use this:
如果要选择所有非空单元格(连续),请使用以下命令:
Range("A1").CurrentRegion.Select
You can then export it in whatever way you fancy ;)
然后你可以以任何你喜欢的方式导出它;)