修剪不同工作表VBA中行和列中的单元格值

时间:2018-11-21 10:18:53

标签: excel vba excel-vba trim spaces

我想修剪其中有空格的单元格。但是我现在拥有的宏不起作用。

Sub DoSomething()

    'Declare Variables
    Dim i, r, c, count, lastColData, LastRowData, lastRowInput, StartSearch As Long
    Dim shtData, shtInput, shtInputI, shtInputII, shtInputIII, shtInputIV, shtInputV, shtInputVI, shtCopy As Worksheet
    Dim Cell As Range
    Set shtData = Sheets("PQFR")
    Set shtInput = Sheets("INPUT")
    Set shtInputI = Sheets("INPUTI")
    Set shtInputII = Sheets("INPUTII")
    Set shtInputIII = Sheets("INPUTIII")
    Set shtInputIV = Sheets("INPUTIV")
    Set shtInputV = Sheets("INPUTV")
    Set shtInputVI = Sheets("INPUTVI")
    Set shtCopy = Sheets("INPUTR")
    lastColData = shtData.Cells(4, shtData.Columns.count).End(xlToLeft).Column
    LastRowData = shtData.Cells(shtData.Rows.count, "A").End(xlUp).row
    lastRowInput = shtInputI.Cells(shtInputI.Rows.count, "A").End(xlUp).row
    'lastRowData = 10


    'Remove spaces from these sheets:
    shtInput.Cells(r, 32).Value = Trim(shtInput.Cell(r, 32).Value)
    shtInputI.Cells(4, c).Value = Trim(shtInputI.Cells(4, c)).Value
    shtInputII.Cells(4, c).Value = Trim(shtInputII.Cell(4, c)).Value
    shtInputIII.Cells(4, c).Value = Trim(shtInputIII.Cell(4, c)).Value
    shtInputIV.Cells(4, c).Value = Trim(shtInputIV.Cells(4, c)).Value

End Sub

1 个答案:

答案 0 :(得分:0)

这是因为您没有进行循环。如果您能更好地向我解释您想要什么,我可以随您便便。

Dim i, r, c, count, lastColData, LastRowData, lastRowInput, StartSearch As Long


For Each Worksheet In ActiveWorkbook.Worksheets
    If Worksheet.Name = "PQFR" Or Worksheet.Name = "INPUT" Then 'please do for the sheets you want your command gonna`s be executed
        Sheets(Worksheet.Name).Select
        lastColData = Cells(4,Columns.count).End(xlToLeft).Column
        LastRowData = Cells(Rows.count, 1).End(xlUp).Row
        lastRowInput = Cells(Rows.count, 1).End(xlUp).Row

        'using c=32 just for input
        If Worksheet.Name = "INPUT" Then
            'using r = 4 fosheets
            For c = 32 To lastColData
                For r = 1 To LastRowData
                    Cells(r, c) = Trim(Cells(r, c).Value)
                Next r
            Next c
        Else
            'using r = 4 for all the other sheets
            For c = 1 To lastColData
                For r = 4 To LastRowData
                    Cells(r, c) = Trim(Cells(r, c).Value)
                Next r
            Next c
        End If
    End If
Next Worksheet