2015-04-01 68 views
0

我拼命想創建一個宏,這將讓我做到以下幾點:找到比數據的情況下更多的文本文件

  1. 選擇文本文件(不同的一個每次)
  2. 看數據並識別關鍵短語,如第一個實例「_ _Z_1 _:_」
  3. 然後這句話
  4. 寫到Excel
  5. 然後找出關鍵短語的下一個實例如下提取數據
  6. 提取數據
  7. 寫入到Excel

任何幫助非常讚賞。

我真的不知道該怎麼做。我的代碼如下:

Private Sub CommandButton1_Click() 
Dim myFile As String, text As String, textline As String, Day As String, Zno As String, NetSales As String, Cash As String, Card As String, HotDrinks As String, ColdDrinks As String, Sweets As String, Crisps As String, VAT As String, NextZ As String 

myFile = Application.GetOpenFilename() 

Dim bffr As String, p As Long 
bffr = (myFile) 
p = InStr(p + 1, bffr, "_ _Z_1_:_", vbTextCompare) 
Do While CBool(p) 

'_ _Z_1_:_ was found; process it based upon the starting position p 

'see if there are other occurrences of _ _Z_1_:_ 
p = InStr(p + 1, bffr, "_ _Z_1_:_", vbTextCompare) 
Loop 

Open myFile For Input As #1 
Do Until EOF(1) 
Line Input #1, textline 
text = text & textline 
Loop 
Close #1 

Day = InStr(text, "Welcome Bite") 
Zno = InStr(text, "_ _Z_1_:_") 
NetSales = InStr(text, "NET sales   ") 
Cash = InStr(text, "CASH in ") 
Card = InStr(text, "CREDIT in") 
HotDrinks = InStr(text, "HOT DRINKS   ") 
ColdDrinks = InStr(text, "COLD DRINKS  ") 
Sweets = InStr(text, "Sweets    ") 
Crisps = InStr(text, "Crisps    ") 
VAT = InStr(text, "** Fixed Totaliser Period 1 Totals Reset") 
NextZ = InStr(text, "_ _Z_1_:_") 


Range("A1").Value = Mid(text, Day + 19, 18) 
Range("A2").Value = Mid(text, Zno + 10, 8) 
Range("A3").Value = Mid(text, NetSales + 30, 7) 
Range("A4").Value = Mid(text, Cash + 30, 7) 
Range("A5").Value = Mid(text, Card + 30, 7) 
Range("A6").Value = Mid(text, HotDrinks + 30, 7) 
Range("A7").Value = Mid(text, ColdDrinks + 30, 7) 
Range("A8").Value = Mid(text, Sweets + 30, 7) 
Range("A9").Value = Mid(text, Crisps + 30, 7) 
Range("A10").Value = Mid(text, VAT - 9, 7) 

Range("B2").Value = Mid(text, p + 1, 8) 


End Sub 

回答

0

至於能夠每次選擇不同的文件,你可以使用

with application.filedialog(msoFileDialogOpen) 
'disallows the user from selecting more than one file at a time 
.allowmultiselect=false 
'shows the file open dialog box 
.show 

if .selecteditems.count=0 then 
'dismisses dialog box if no selection 
else 
strPath=.selecteditems(1) 
end if 
end with 

然後可以使用strPath來讀取文本,雖然方式我從文本文件中完成閱讀是將文本右側寫入工作簿中的隱藏工作表(在Do Until EOF(1)循環中使text=textline並在此之後添加[workbookname].sheet([sheetname]).cells(xrowx,1)=textxrowx=xrowx+1)。這種格式的信息更易於管理,而不是試圖從一個巨大的字符串中讀取。給它一個旋轉,看看它是否讓你更容易。

+0

謝謝!我會去的! – 2015-04-02 10:01:19

相關問題