2015-04-14 84 views
0

我一直試圖做一段時間,但我很難過。我試圖通過選擇循環,以便我可以獲取一些信息並將其保存在文本文件中。它的工作原理除了當選擇不在列A中開始時,一些數據不會被帶入到文本文件中(它將列(1)作爲選擇中的第一列)。代碼如下:選擇第一列(A),而不是選擇中的第一列(VBA-Excel)

Sub SaveInfoTxtFile() 

Dim oCell As Range 
Dim myRange As Range 
Dim fso As Object 
Dim oFile As Object 
Dim LastRow As Long 
Dim wholeselect As String 

Dim year As String 
Dim make As String 
Dim model As String 

Set myRange = Selection 
LastRow = ActiveSheet.Cells(ActiveSheet.Rows.Count, "A").End(xlUp).Row 
wholeselect = CStr(myRange.Row) & ":" & CStr(LastRow) 
Set fso = CreateObject("Scripting.FileSystemObject") 
Set oFile = fso.CreateTextFile("C:\SSE\test.txt") 

Rows(wholeselect).Select 

For Each oCell In myRange 

year = oCell.Columns(1).Text 
make = oCell.Columns(2).Text 
model = oCell.Columns(3).Text 

oFile.WriteLine year & " " & make & " " & model 
oFile.WriteLine 

Next oCell 

oFile.WriteLine "Name: Blah" 
oFile.WriteLine "Company: Blah2" 
oFile.Close 
Set fso = Nothing 
Set oFile = Nothing 

End Sub 

建議?

+0

你有'Set myRange = Selection'其他代碼'For Each oCell In myRange'。你是不是說'For Each'要超過不同的範圍? –

回答

0

這裏有兩個方法來解決這個問題:

year = oCell.EntireRow.Columns(1).Text 

恕我直言,這將是最好設置在你循環,使整個行合併範圍。在循環內執行效率較低。

set myRange = rows(wholeselect).EntireRow 
For Each oCell In myRange 
... 
+0

非常感謝你,改變你的想法解決了問題! –

+0

很高興你解決了你的問題。如果您對我的答案滿意,請點擊它將狀態更改爲「已接受」。 – user1016274

相關問題