【发布时间】:2016-09-28 01:23:45
【问题描述】:
这是我当前的代码。
Sub Loops()
Dim MyPath As String
Dim MyFileName As String
Dim output As Variant
Dim outputRange(1 To 3) As Range
Set outputRange(1) = Worksheets("vbaTest").Range("output1", Worksheets("vbaTest").Range("output1").End(xlDown))
Set outputRange(2) = Worksheets("vbaTest").Range("output2", Worksheets("vbaTest").Range("output2").End(xlDown))
Set outputRange(3) = Worksheets("vbaTest").Range("output3", Worksheets("vbaTest").Range("output3").End(xlDown))
For Each output In outputRange
'The path and file names:
MyPath = "C:\Users\x\Custom Office Templates"
MyFileName = "Test"
'Makes sure the path name ends with "\":
If Not Right(MyPath, 1) = "\" Then MyPath = MyPath & "\"
'Makes sure the filename ends with ".csv"
If Not Right(MyFileName, 4) = ".txt" Then MyFileName = MyFileName & ".txt"
'Copies the sheet to a new workbook:
Sheets("vbaTest").Range("**output1**").Copy
'The new workbook becomes Activeworkbook:
Workbooks.Add
ActiveSheet.Columns("A").Select
Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
:=False, Transpose:=False
With ActiveWorkbook
Application.DisplayAlerts = False
End With
'Brings back original sheet
Workbooks("vbaTest.csv").Activate
'Starts at the top of code
Next output
End Sub
当涉及到 output1 时,我无法循环遍历我设置的不同范围。 "Sheets("vbaTest").Range("output1").Copy"
我试图让 vba 循环遍历我设置的其他三个输出。有什么建议吗?
【问题讨论】:
-
您希望该部分更改为不同的输出范围,对吗?
Sheets("vbaTest").Range(output.address).Copy不行吗? -
是的。它刚刚奏效。我昨天开始使用 VBA,并且我已经被困在这一点上好几个小时了。非常感谢!
-
只使用
output.Copy,因为输出已经是Range(虽然通过Variantlens)