2015-06-17 99 views
0

我在Excel中有一個二維圖表。我需要使用兩個字符串變量來獲取單元格的值。圖表看起來是這樣的:獲取兩個字符串變量的單元格值

Document  person1 person2 
Text1  5   8 
Text2  2   1 
Text3  9   6 

網上找我發現在這之後很困難,因爲:

  1. 的值是字符串,不是整數;
  2. 字符串將根據哪個人和文檔組合出現而改變。

這應該是相關的唯一代碼:假設文件和個人持有整數的字符串表示(是字符串變量

Dim document as string 
Dim person as string 

Dim oExcel as excel.application 
Dim oWB as workbook 
Set oExcel = New Excel.application 
Set oWB = oExcel.Workbooks.open.  ("C:") 
oExcel.Visible = True 

oWB.Sheets ("sheet1").Cells(documemt, person) 

回答

0

如文檔=「1」,人=「2」 )然後像

oWB.Sheets ("sheet1").Cells(val(document), val(person)) 

將工作。如果字符串變量的內容更復雜,那麼您需要對這些字符串進行一些解析。

0

通過「2D圖表」假設您是指工作表中的表格,並且該人員將是全文「person1」或「person2」等,並且對於文檔同樣如此,那麼也許該函數將執行該操作。

Function FindDocPerson(person As String, document As String) As Variant 
    Const MatchExact As Integer = 0 
    Dim ws As Excel.Worksheet 
    Set ws = ActiveWorkbook.Worksheets("Sheet1") 

    Dim table As Excel.Range 
    Set table = ws.UsedRange 

    Dim docRange As Excel.Range 
    Set docRange = table.Columns(1).Offset(1, 0).Resize(table.Columns(1).Rows.Count - 1) 

    Dim personRange As Excel.Range 
    Set personRange = table.Rows(1).Offset(0, 1).Resize(1, table.Columns.Count - 1) 

    Dim personIndex As Long 
    Dim docIndex As Long 

    On Error GoTo errHandler 

    personIndex = Application.WorksheetFunction.Match(person, personRange, MatchExact) + 1 
    docIndex = Application.WorksheetFunction.Match(document, docRange, MatchExact) + 1 
    FindDocPerson = table.Cells(docIndex, personIndex).Value2 
    Exit Function 

errHandler: 
    FindDocPerson = VBA.CVErr(Excel.xlErrNA) 
End Function 

調用語法:

Dim result As Variant 
result = FindDocPerson("person2", "text1") 

If Application.WorksheetFunction.IsError(result) Then 
    ' handle it 
Else 
    ' found it 
End If 
0

有一個在你的代碼一個錯字,

oWB.Sheets ("sheet1").Cells(documemt, person) 

documemt應該是文件

所有,雖然一邊還不清楚你想要什麼要做什麼,你可以多給一點描述嗎?

我們所知道的是,您需要使用兩個字符串變量來獲取單元格的值,並且它可以是字符串或數字。你發佈的代碼並沒有給你提供更多的暗示。

要在字符串和數字之間進行轉換,可以使用CLng轉換爲長數字或CStr轉換爲字符串。如CLng函數( 「3」)= 3,CStr的(3)= 「3」

在您的代碼如下:

Set oWB = oExcel.Workbooks.open.  ("C:") 

不工作,因爲你試圖打開工作簿時沒有指定名稱,我還注意到(「C:」)在命令調用的右側很遠,這導致我相信這是已經鍵入的自由式,即不在VBE中。這使解碼成您的需求更加困難。

最後,此代碼:

Set oExcel = New Excel.application 

你爲什麼從Excel VBA代碼啓動Excel的另一個會話?此代碼是否在Excel以外的地方,例如Outlook/Access/PowerPoint/Word/Business Objects等等。

相關問題