在Excel中重组数据

时间:2013-08-19 11:29:26

标签: vb.net excel

我正在使用VB创建一个宏,它将重新组织列并确定标题的列顺序。

下面的代码工作正常,但是一旦我运行代码,系统会提示我输入我想要使用的工作表的名称:'指定需要重新组织的工作表的名称'(答案:'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

1 个答案:

答案 0 :(得分:0)

有两种方法可以避免出现提示。

一种是在函数中定义工作表。 e.g。

data_sheet1 = "Sheet1"

代替data_sheet1 = inputbox(...行。

另一种是将表单名称传递给函数,例如

Sub MoveColumns(data_sheet1 as String)

然后完全删除data_sheet1 = inputbox(...行。您必须将调用例程的代码从MoveColumns更改为MoveColumns "Sheet1",但随后您可以放置​​所需的任何工作表名称,并多次调用它。 e.g。

MoveColumns "Sheet1"
MoveColumns "budget"
MoveColumns "MyVeryLongSheetName2047"