-1

我正在使用 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
4

1 回答 1

0

想到2种方法来不出现提示。

一种是在函数内定义工作表。例如

data_sheet1 = "Sheet1"

代替data_sheet1 = inputbox(...线。

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

Sub MoveColumns(data_sheet1 as String)

然后完全删除data_sheet1 = inputbox(...线。您必须将调用例程的代码从 更改MoveColumnsMoveColumns "Sheet1",但随后您可以输入任何您想要的工作表名称,并多次调用它。例如

MoveColumns "Sheet1"
MoveColumns "budget"
MoveColumns "MyVeryLongSheetName2047"
于 2013-08-19T13:44:42.983 回答