2016-09-07 70 views
0

我試圖從另一個表格打開一個spredsheet,以使其不在視圖中。然後我想使用TextToColumns功能將其中一列的列格式更改爲日期。然後應該保存更改並自動關閉文件。使用VBA修改已關閉的Excel表格

當我運行以下它說沒有數據被選中解析。有什麼想法嗎?

Sub Test() 

Dim xlApp As New Excel.Application 
Dim xlWB As Excel.Workbook 
Dim xlWS As Excel.Worksheet 

xlApp.Visible = False 

Set xlWB = xlApp.Workbooks.Open("directory of file") 

Set xlWS = xlWB.Worksheets("Sheet 1") 
xlWS.Unprotect 


    xlWS.Columns("F:F").Select 
    Selection.TextToColumns Destination:=Range("F1"), DataType:=xlDelimited, _ 
     TextQualifier:=xlDoubleQuote, ConsecutiveDelimiter:=False, Tab:=True, _ 
     Semicolon:=False, Comma:=False, Space:=False, Other:=False, FieldInfo _ 
     :=Array(1, 4), TrailingMinusNumbers:=True 


Set xlWS = Nothing 
xlApp.DisplayAlerts = False 
xlWB.Close True 
Set xlWB = Nothing 
xlApp.Quit 
Set xlApp = Nothing 

End Sub 
+0

做什麼你的意思是關閉?你的意思是表單所在的工作簿已關閉?或者你的意思是說另一張表有重點? – gizlmo

+0

有兩個小工具。一個是開放的。另一個不是。我希望打開的一個在後臺打開第二個,更改某些列的數據類型。保存更改並關閉隱藏的工作簿。 – kit

回答

0

的研究有點應該給你的結果,但我無論如何都會提供它...

'Since you want the Workbook to be invisible, we have to open it in a new Excel Application 
Dim xlApp As New Excel.Application 
Dim xlWB As Excel.Workbook 
Dim xlWS As Excel.Worksheet 

xlApp.Visible = False 

'Open Workbook from specified path 
Set xlWB = xlApp.Workbooks.Open("YOUR FILEPATH HERE") 

'Select Worksheet from opened Workbook 
Set xlWS = xlWB.Worksheets("YOUR WORKSHEET NAME HERE") 

'Do something 
'example 
xlWS.Name = "Asdf" 

'Cleanup 
Set xlWS = Nothing 
xlWB.Close 'True to save changes, False to discard changes 
Set xlWB = Nothing 
xlApp.Quit 
Set xlApp = Nothing 
+0

非常感謝您的幫助。要保存更改,您更改爲True? – kit

+0

'xlWB.Close True''而不是'xlWB.Close' – gizlmo

+0

當你這樣做時,它會調出另存爲窗口。我曾嘗試使用xlApp.DisplayAlerts = False。你知道如何在不提示的情況下保存當前文件嗎? – kit

0

這應該讓你開始...

Sub Test() 

    Dim wbk As Workbook 

    'Open the workbook that is closed 
    Set wbk = Workbooks.Open("C:\OtherWorkbook.xlsx") 

    'Change the format of the first column 
    wbk.Worksheets(1).Range("A:A").NumberFormat = "0.00" 

    'Close the workbook and save changes 
    wbk.Close True 


End Sub