Excel VBA:让编辑栏显示单元格值而非公式及变量替代RC引用问题
解决方案
1. 让编辑栏显示单元格值而非公式
要让单元格存储具体数值而非公式,直接在VBA中计算出匹配的Sales结果,赋值给单元格的Value属性即可,无需设置FormulaArray。修改代码如下:
lastRow = Range("A1").End(xlDown).Row lastColumn = Range("A1").End(xlRight).Column For i = 2 To lastRow shopName = Cells(i, 1).Value For j = 2 To lastColumn shopRegion = Cells(1, j).Value ' 直接计算并写入结果 Cells(i, j).Value = Application.Index(Shop[Sales], _ Application.Match(1, (Shop[Name] = shopName) * (Shop[Region] = shopRegion), 0)) Next j Next i
如果需要保留数组公式的计算逻辑再转值,也可以先写入公式,再覆盖为计算结果:
' 写入数组公式 Cells(i,j).FormulaArray = "=Index(Shop[Sales], Match(1, (RC[" & (1- j) & "] = Shop[Name])*(R[" & (1- i) & "]C = Shop[Region]), 0))" ' 将公式结果转为单元格值 Cells(i,j).Value = Cells(i,j).Value
2. 用shopName和shopRegion变量替代RC相对引用
可以直接把变量值拼接进数组公式字符串,注意文本类型变量需要用双引号包裹(VBA中通过两个双引号表示一个实际双引号)。修改后的代码如下:
Cells(i,j).FormulaArray = "=Index(Shop[Sales], Match(1, (""" & shopName & """ = Shop[Name])*(""" & shopRegion & """ = Shop[Region]), 0))"
这样公式直接使用变量对应的店铺名称和区域值,不再依赖RC的相对引用定位。
内容的提问来源于stack exchange,提问作者M J
相关产品推荐
相关产品推荐

