2015-06-15 6 views
0

Я искал, чтобы создать программу, которая проверила колонку текста в excel и извлекла первую строку, содержащую валюту. Валюта была в канадских долларах и отформатирована в «C $ ##. ##» без каких-либо известных ограничений, но вряд ли достигнет 10 000 долларов. Я надеялся сделать эту операцию 500 раз и сохранить результаты в листе мастера.Изменение активной ячейки

Я новичок в VBA в excel и буду благодарен за любую помощь по следующему коду. Проблема, с которой я сталкиваюсь, - неспособность изменить активный лист. Сценарий возвращает #Value! и не проходит мимо строки «SaSh.Range (« A1 »). Выберите«.

Option Explicit 
Public NewValue As Integer 'Amount of Money current item is being sold for 

Function PriceOfGoods(SaleString As String) 

    Dim SaleSheet As Worksheet 

    Set SaleSheet = Worksheets(SaleString) 

    NewValue = -1 

    Call PriceSearch(SaleSheet) 

    PriceOfGoods = NewValue 

End Function 

Public Sub PriceSearch(SaSh As Worksheet) 

    Dim StartNumber As Integer 
    Dim EndNumber As Integer 
    Dim CurrentCell As String 

    EndNumber = 1000 

    'Activating the Query Sheet and starting search at the top left corner of the sheet 
    SaSh.Range("A1").Select 

    'Keep searching the A column until you come across the Canadian Currency post 
    For StartNumber = 1 To EndNumber 

     CurrentCell = ActiveCell.Value 

     'Checking to see if the current cell is Canadian Currency 
     If WorksheetFunction.IsNumber(CurrencyValuation(CurrentCell)) Then 

      NewValue = CurrencyValuation(ActiveCell.Value) 
      Exit For 

     End If 

     'Continue search in the next row 
     ActiveCell.Offset(1, 0).Select 

    Next StartNumber 

End Sub 

Function CurrencyValuation(CurrencyInput As String) 

Dim NewCurrency As Integer 

NewCurrency = WorksheetFunction.Substitute(CurrencyInput, "C", "") 

CurrencyValuation = NewCurrency 

End Function 
+0

вы смотрели на любые потенциальные проблемы с Саш, когда вы проходите это в функцию PriceSearch? – Paradox

+1

Функция, вызываемая из ячейки листа, ограничена в том, что она может сделать: https://support.microsoft.com/en-us/kb/170787 Вы можете переписать свой 'PriceSearch', чтобы избежать использования' ActiveCell' и 'Select ' –

+0

Постарайтесь быть более конкретным. т. е. YourWorkbook.YourWorksheet.Range («A1»). Выберите – Paradox

ответ

0

Замечания, сделанные @Paradox и @Tim, действительны.

Чтобы конкретно ответить на ваш вопрос, вы не можете изменить ActiveCell из кода, но вместо того, чтобы использовать Range или Cells установить ссылку на диапазон:

Public Sub PriceSearch(SaSh As Worksheet) 

    Dim StartNumber As Integer 
    Dim EndNumber As Integer 
    Dim CellToCheck As Range 

    EndNumber = 1000 

    'Search the Query Sheet and starting search at the top left corner of the sheet 
    'Keep searching the A column until you come across the Canadian Currency post 
    For StartNumber = 1 To EndNumber 

     Set CellToCheck = SaSh.Cells(RowIndex:=StartNumber, ColumnIndex:=1) 

     'Checking to see if the current cell is Canadian Currency 
     If WorksheetFunction.IsNumber(CurrencyValuation(CellToCheck.Value)) Then 
      NewValue = CurrencyValuation(CellToCheck.Value) 
      Exit For 
     End If 
    Next StartNumber 

End Sub 
+0

Благодарим за помощь. – user3429358

Смежные вопросы