2013-08-19 50 views
-1

我正在使用VB創建一個宏的過程,該宏將重新組織列並確定標題的列順序。在Excel中重組數據

下面的代碼工作正常,但是一旦我運行代碼,系統會提示我輸入希望使用的工作表名稱:'指定需要重新組織的工作表名稱'(答案:' Sheet1')

你能告訴我有無論如何我可以運行下面的代碼沒有Excel提示我輸入我希望改變數據的表的名稱?

'REARRANGE COLUMNS IN EXCEL BASED ON COLUMN HEADER 
Sub MoveColumns() 
Dim iRow As Long 
Dim iCol As Long 

'CONSTANT VALUES 
data_sheet1 = InputBox("Specify the name of the Sheet that needs to be reorganised:") 
target_sheet = "Final Report" 
iRow = Sheets(data_sheet1).UsedRange.Rows.Count 

'CREATE A NEW SHEET TO STORE THE RESULTS 
Worksheets.Add.Name = "Final Report" 

'ORGANIZE COLUMNS 
For iCol = 1 To Sheets(data_sheet1).UsedRange.Columns.Count 

    'SETS THE TARGETCOL TO ZERO IN ORDER TO PREVENT OVERWRITING EXISTING TARGETCOLUMNS 
    TargetCol = 0 

    'DETERMINE COLUMN ORDER 
    If Sheets(data_sheet1).Cells(1, iCol).Value = "billing_country" Then TargetCol = 1 
    If Sheets(data_sheet1).Cells(1, iCol).Value = "partner_accountname" Then TargetCol = 2 
    If Sheets(data_sheet1).Cells(1, iCol).Value = "partner_number" Then TargetCol = 3 
    If Sheets(data_sheet1).Cells(1, iCol).Value = "pbl_due_date" Then TargetCol = 4 
    If Sheets(data_sheet1).Cells(1, iCol).Value = "total_amount" Then TargetCol = 5 
    If Sheets(data_sheet1).Cells(1, iCol).Value = "pb_payment_currency" Then TargetCol = 6 
    If Sheets(data_sheet1).Cells(1, iCol).Value = "sort_code" Then TargetCol = 7 
    If Sheets(data_sheet1).Cells(1, iCol).Value = "cda_number" Then TargetCol = 8 

    'If a TargetColumn was determined (based upon the header information) then copy the column to the right spot 
    If TargetCol <> 0 Then 
     'Select the column and copy it 
     Sheets(data_sheet1).Range(Sheets(data_sheet1).Cells(1, iCol), Sheets(data_sheet1).Cells(iRow, iCol)).Copy Destination:=Sheets(target_sheet).Cells(1, TargetCol) 
    End If 

Next iCol 'Move to the next column until all columns are read 

End Sub 
+0

不使用'InputBox'? – SeanC

+0

我明白你的意思,但我只是從某處(我是VB新手!)複製這段代碼,當我嘗試刪除輸入框時,它不起作用。除了你知道的inputbox之外,還有其他的方法嗎?謝謝你的幫助。 – user2682287

回答

0

2個方法想到沒有提示出現。

一個是在函數內定義表單。例如

data_sheet1 = "Sheet1" 

代替data_sheet1 = inputbox(...行。

另一個是將表格名稱傳遞給函數,例如,

Sub MoveColumns(data_sheet1 as String) 

然後完全刪除data_sheet1 = inputbox(...一行。您必須將調用例程的代碼從MoveColumns更改爲MoveColumns "Sheet1",但您可以將所需的任何工作表名稱更改爲多次。例如

MoveColumns "Sheet1" 
MoveColumns "budget" 
MoveColumns "MyVeryLongSheetName2047" 
+0

第一部分:data_sheet1 =「Sheet1」工作完美,感謝您的幫助! – user2682287